[转]Design Pattern Interview Questions - Part 2

Interpeter , Iterator , Mediator , Memento and Observer design patterns.

 
  • (I) what is Interpreter pattern?
  • (B) Can you explain iterator pattern?
  • (A) Can you explain mediator pattern?
  • (I) Can you explain memento pattern?
  • (B) Can you explain observer pattern?
Other Interview question PDF's

Introduction

Again i repeat do not think you get an architecture position by reading interview questions. But yes there should be some kind of reference which will help you quickly revise what are the definition. Just by reading these answers you get to a position where you are aware of the fundamentals. But if you have not really worked you will surely fail with scenario based questions. So use this as a quick revision rather than a shot cut.

In case your are completely new to design patterns or you really do not want to read this complete  article do see our free design pattern Training and interview questions / answers videos.

If you have not read my pervious section you can always read from below

  • Part 1 Design pattern interview questions http://www.dotnetfunda.com/articles/article130.aspx 
  • Part 3 Design Pattern Interview Questions :- http://www.dotnetfunda.com/articles/article137.aspx
  • Part 4 Design pattern Interview Questions :- http://www.dotnetfunda.com/articles/article139.aspx

Happy job hunting......

(I) what is Interpreter pattern?

Interpreter pattern allows us to interpret grammar in to code solutions. Ok, what does that mean?. Grammars are mapped to classes to arrive to a solution. For instance 7 – 2 can be mapped to ‘clsMinus’ class. In one line interpreter pattern gives us the solution of how to write an interpreter which can read a grammar and execute the same in the code. For instance below is a simple example where we can give the date format grammar and the interpreter will convert the same in to code solutions and give the desired output.

Figure: - Date Grammar


Let’s make an interpreter for date formats as shown in figure ‘Date Grammar’. Before we start lets understand the different components of interpreter pattern and then we will map the same to make the date grammar. Context contains the data and the logic part contains the logic which will convert the context to readable format.

Figure: - Context and Logic


Let’s understand what is the grammar in the date format is. To define any grammar we should first break grammar in small logical components. Figure ‘Grammar mapped to classes’ show how different components are identified and then mapped to classes which will have the logic to implement only that portion of the grammar. So we have broken the date format in to four components Month, Day, Year and the separator. For all these four components we will define separate classes which will contain the logic as shown in figure ‘Grammar mapped to classes’. So we will be creating different classes for the various components of the date format.

Figure: - Grammar mapped to classes


As said there are two classes one is the expression classes which contain logic and the other is the context class which contain data as shown in figure ‘Expression and Context classes’. We have defined all the expression parsing in different classes, all these classes inherit from common interface ‘ClsAbstractExpression’ with a method ‘Evaluate’. The ‘Evaluate’ method takes a context class which has the data; this method parses data according to the expression logic. For instance ‘ClsYearExpression’ replaces the ‘YYYY’ with the year value,’’ClsMonthExpression’ replaces the ‘MM’ with month and so on.

Figure :- Class diagram for interpreter

Figure: - Expression and Context classes


Now that we have separate expression parsing logic in different classes, let’s look at how the client will use the iterator logic. The client first passes the date grammar format to the context class. Depending on the date format we now start adding the expressions in a collection. So if we find a ‘DD” we add the ‘ClsDayExpression’, if we find ‘MM’ we add ‘ClsMonthExpression’ and so on. Finally we just loop and call the ‘Evaluate’ method. Once all the evaluate methods are called we display the output.

Figure: - Client Interpreter logic

Note :- You can find the code for interpreter in ‘Interpeter’ folder.

(B) Can you explain iterator pattern?

Iterator pattern allows sequential access of elements with out exposing the inside code. Let’s understand what it means. Let’s say you have a collection of records which you want to browse sequentially and also maintain the current place which recordset is browsed, then the answer is iterator pattern. It’s the most common and unknowingly used pattern. Whenever you use a ‘foreach’ (It allows us to loop through a collection sequentially) loop you are already using iterator pattern to some extent.

Figure: - Iterator business logic


In figure ‘Iterator business logic’ we have the ‘clsIterator’ class which has collection of customer classes. So we have defined an array list inside the ‘clsIterator’ class and a ‘FillObjects’ method which loads the array list with data. The customer collection array list is private and customer data can be looked up by using the index of the array list. So we have public function like ‘getByIndex’ ( which can look up using a particular index) , ‘Prev’ ( Gets the previous customer in the collection , ‘Next’ (Gets the next customer in the collection), ‘getFirst’ ( Gets the first customer in the collection ) and ‘getLast’ ( Gets the last customer in the collection). 

So the client is exposed only these functions. These functions take care of accessing the collection sequentially and also it remembers which index is accessed. 

Below figures ‘Client Iterator Logic’ shows how the ‘ObjIterator’ object which is created from class ‘clsIterator’ is used to display next, previous, last, first and customer by index.

Figure: - Client Iterator logic


Note :- You can get a sample C# code in the ‘Iterator’ folder of the CD provided with this book.

(A) Can you explain mediator pattern?


Many a times in projects communication between components are complex. Due to this the logic between the components becomes very complex. Mediator pattern helps the objects to communicate in a disassociated manner, which leads to minimizing complexity.

Figure: - Mediator sample example


Let’s consider the figure ‘Mediator sample example’ which depicts a true scenario of the need of mediator pattern. It’s a very user-friendly user interface. It has three typical scenarios.
Scenario 1:- When a user writes in the text box it should enable the add and the clear button. In case there is nothing in the text box it should disable the add and the clear button.

Figure: - Scenario 1


Scenario 2:- When the user clicks on the add button the data should get entered in the list box. Once the data is entered in the list box it should clear the text box and disable the add and clear button.

Figure: - Scenario 2


Scenario 3:- If the user click the clear button it should clear the name text box and disable the add and clear button.

Figure: - Scenario 3


Now looking at the above scenarios for the UI we can conclude how complex the interaction will be in between these UI’s. Below figure ‘Complex interactions between components’ depicts the logical complexity.

Figure: - Complex interactions between components


Ok now let me give you a nice picture as shown below ‘Simplifying using mediator’. Rather than components communicating directly with each other if they communicate to centralized component like mediator and then mediator takes care of sending those messages to other components, logic will be neat and clean.

Figure: - Simplifying using mediator

Now let’s look at how the code will look. We will be using C# but you can easily replicate the thought to JAVA or any other language of your choice. Below figure ‘Mediator class’ shows the complete code overview of what the mediator class will look like.


The first thing the mediator class does is takes the references of the classes which have the complex communication. So here we have exposed three overloaded methods by name ‘Register’. ‘Register’ method takes the text box object and the button objects. The interaction scenarios are centralized in ‘ClickAddButton’,’TextChange’ and ‘ClickClearButton’ methods. These methods will take care of the enable and disable of UI components according to scenarios.

Figure: - Mediator class


The client logic is pretty neat and cool now. In the constructor we first register all the components with complex interactions with the mediator. Now for every scenario we just call the mediator methods. In short when there is a text change we can the ‘TextChange’ method of the mediator, when the user clicks add we call the ‘ClickAddButton’ and for clear click we call the ‘ClickClearButton’.

Figure: - Mediator client logic


Note :- You can get the C# code for the above mediator example in the ‘mediator’ folder.

(I) Can you explain memento pattern?


Memento pattern is the way to capture objects internal state with out violating encapsulation. Memento pattern helps us to store a snapshot which can be reverted at any moment of time by the object. Let’s understand what it means in practical sense. Consider figure ‘Memento practical example’, it shows a customer screen. Let’s say if the user starts editing a customer record and he makes some changes. Later he feels that he has done something wrong and he wants to revert back to the original data. This is where memento comes in to play. It will help us store a copy of data and in case the user presses cancel the object restores to its original state.

Figure: - Memento practical example


Let’s try to complete the same example in C# for the customer UI which we had just gone through. Below is the customer class ‘clsCustomer’ which has the aggregated memento class ‘clsCustomerMemento’ which will hold the snapshot of the data. The memento class ‘clsCustomerMemento’ is the exact replica ( excluding methods ) of the customer class ‘clsCustomer’. When the customer class ‘clsCustomer’ gets initialized the memento class also gets initialized. When the customer class data is changed the memento class snapshot is not changed. The ‘Revert’ method sets back the memento data to the main class.

Figure: - Customer class for memento

The client code is pretty simple. We create the customer class. In case we have issues we click the cancel button which in turn calls the ‘revert’ method and reverts the changed data back to the memento snapshot data. Figure ‘Memento client code’ shows the same in a pictorial format.

Figure: - Memento client code

Note :- A sample code in C# for memento is available in the memento folder of the CD.

(B) Can you explain observer pattern?


Observer pattern helps us to communicate between parent class and its associated or dependent classes. There are two important concepts in observer pattern ‘Subject’ and ‘Observers’. The subject sends notifications while observers receive notifications if they are registered with the subject. Below figure ‘Subject and observers’ shows how the application (subject) sends notification to all observers (email, event log and SMS). You can map this example to publisher and subscriber model. The publisher is the application and subscribers are email, event log and sms.

Figure: - Subject and Observers


Let’s try to code the same example which we have defined in the previous section. First let’s have a look at the subscribers / notification classes. Figure ‘Subscriber classes’ shows the same in a pictorial format. So we have a common interface for all subscribers i.e. ‘INotification’ which has a ‘notify’ method. This interface ‘INotification’ is implemented by all concrete notification classes. All concrete notification classes define their own notification methodology. For the current scenario we have just displayed a print saying the particular notification is executed.

Figure: - Subscriber classes


As said previously there are two sections in an observer pattern one is the observer/subscriber which we have covered in the previous section and second is the publisher or the subject.

The publisher has a collection of arraylist which will have all subscribers added who are interested in receiving the notifications. Using ‘addNotification’ and ‘removeNotification’ we can add and remove the subscribers from the arraylist. ‘NotifyAll’ method loops through all the subscribers and send the notification.

Figure: - Publisher/Subject classes


Now that we have an idea about the publisher and subscriber classes lets code the client and see observer in action. Below is a code for observer client snippet. So first we create the object of the notifier which has collection of subscriber objects. We add all the subscribers who are needed to be notified in the collection.
Now if the customer code length is above 10 characters then tell notify all the subscribers about the same.

Figure: - Observer client code


Note :- You can get the C# code snippet for observer pattern from the CD in ‘Observer’ folder.

转载于:https://www.cnblogs.com/yfdream/p/3511193.html

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/273884.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

python爬虫面试题

1 :列表生成式和生成器的区别 ? 列表生成式直接生成一个列表,所有元素对象被立即创建在内存中,当元素过多时,势必会占用过多内存, 不可取,要用到生成器,它即时创建一个生成器对象,…

%hd %d %ld %u ......

%d 有符号10进制整数 %ld 长整型 %hd短整型%md,m指定的是输出字段的宽度,默认左补空格, 如果数据的位数小于m,则左端补以空格,若大于m,则  按实际位数输出,如:  printf("%4d,%4d",a,b)  若…

我的扑克牌

main.m文件&#xff1a; #import <Foundation/Foundation.h> #import "hearts.h" #import "spade.h" #import "wintersweet.h" #import "diamonds.h" #import "stdio.h" #import "string.h" int main(int a…

在使用selenium,Chrome无界面浏览模式与自定义插件加载问题

Chrome启用无界面浏览模式时&#xff0c;自定义插件是没法加载的&#xff0c;会报以下错误&#xff1a; selenium.common.exceptions.WebDriverException: Message: unknown error: failed to wait for extension background page to load: chrome-extension://cdkhikphdegmcl…

一遍学习,一遍进步

做挨踢这块也快两年了&#xff0c;还是个小白。懂得技术有限&#xff0c;会的东西不多。知道的东西越多越觉得该知道更多东西。新的知识技术更新越来越快。有点应接不暇。 2013很糊涂的过来了。没有看几本书&#xff0c;没有自我提高&#xff0c;有点浑浑噩噩的感觉。单位的工作…

ubuntu18 安装redis-manager

参考&#xff1a;https://blog.csdn.net/momomomomm/article/details/83626147

Ios17个常用代码整理

1.判断邮箱格式是否正确的代码 //利用正则表达式验证 -(BOOL)isValidateEmail:(NSString *)email { NSString *emailRegex "[A-Z0-9a-z._%-][A-Za-z0-9.-]\\.[A-Za-z]{2,4}"; NSPredicate *emailTest [NSPredicate predicateWithFormat:"SELF MATCHES%",…

ubuntu18 激活 pycharm

1、到官网上下载好对应的版本 2、到安装好的pycharm的bin文件夹下&#xff0c;找到 pycharm.vmoptions 和 pycharm64.vmoptions&#xff0c;在两个文件后面添加代码&#xff1a; -javaagent:-javaagent:/home/maxzhang/user/pycharm/bin/JetbrainsCrack-release-enc.jar&#…

jquery背景自动切换特效

查看效果网址&#xff1a;http://keleyi.com/a/bjad/4kwkql05.htm 本特效的jquery版本只支持1.9.0以下。代码如下&#xff1a; 1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">2…

pandas和spark的区别

参考&#xff1a;https://blog.csdn.net/u013613428/article/details/78138857

Android ImageView图片自适应

网络上下载下来的图片自适应&#xff1a;android:adjustViewBounds"true"&#xff08;其详细解释在下面&#xff09;<ImageViewandroid:id"id/dynamic_item_image"android:layout_width"wrap_content"android:layout_height"wrap_conten…

Python之IO编程——文件读写、StringIO/BytesIO、操作文件和目录、序列化

BytesIO StringIO操作的只能是str&#xff0c;如果要操作二进制数据&#xff0c;就需要使用BytesIO。BytesIO实现了在内存中读写bytes&#xff0c;我们创建一个BytesIO&#xff0c;然后写入一些bytes&#xff1a; 写入的不是str&#xff0c;而是经过UTF-8编码的bytes。 (1).参考…

都江堰很美-佩服古人_Crmhf的一天

地震遗迹&#xff1a;一条背街&#xff0c;损坏严重&#xff0c;基本没什么人。真正的水利工程&#xff0c;值得每个人学习&#xff1a;转载于:https://www.cnblogs.com/crmhf/p/3823157.html

爬虫的增量式抓取和数据更新

不管是产生新页面&#xff0c;还是原本的页面更新&#xff0c;这种变化都被称为增量&#xff0c; 而爬取过程则被称为增量爬取。那如何进行增量式的爬取工作呢&#xff1f;回想一下爬虫的工作流程&#xff1a; 发送URL请求 ----- 获得响应 ----- 解析内容 ----- 存储内容 我们…

Spring Data JPA初使用 *****重要********

Spring Data JPA初使用我们都知道Spring是一个非常优秀的JavaEE整合框架&#xff0c;它尽可能的减少我们开发的工作量和难度。在持久层的业务逻辑方面&#xff0c;Spring开源组织又给我们带来了同样优秀的Spring Data JPA。通常我们写持久层&#xff0c;都是先写一个接口&#…

flask-笔记

-super() 使用super()保留基模板中定义的原始内容 - link标签&#xff1a; 用来指定当前文档和外部资源的关系。它最常见的是用来链接样式表&#xff0c;也用来创建网站图标(既是网站图标样式也包括移动设备和app图标)。 -csrf: CSRF概念&#xff1a;CSRF跨站点请求伪造(…

MySQL 无法连接

Host localhost is not allowed to connect to this MySQL server 错误 解决办法&#xff1a; C:\Program Files\MySQL\MySQL Server 5.5\my.ini 在[mysqld]下加下面两行&#xff0c; skip-name-resolve skip-grant-tables 重启mysql的windows服务&#xff0c;在mysql命令行界面…

能让你少写1000行代码的20个正则表达式

参考: (1).http://www.codeceo.com/article/20-regular-expressions.html

http请求中的Query String Parameters、Form Data、Request Payload

参考: (1).(http请求参数之Query String Parameters、Form Data、Request Payload) - https://www.jianshu.com/p/c81ec1a547ad

蜜罐

http://www.projecthoneypot.org/home.php转载于:https://www.cnblogs.com/diyunpeng/p/3534507.html