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

Android ImageView图片自适应

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

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

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

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

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

[转帖]好技术领导,差技术领导

团队合作一个优秀的技术领导必然是团队的一份子&#xff0c;他们认为当整个团队成功时自己才称得上成功。他们不仅要做好繁杂和不讨好的本职工作&#xff0c;还要清除项目中的障碍&#xff0c;从而让整个团队能够以100%的效率运转起来。一个好的技术领导会努力拓宽团队在技术上…

C#打开文件对话框和文件夹对话框

打开文件对话框OpenFileDialog OpenFileDialog ofd new OpenFileDialog();ofd.Filter "Excel文件(*.xls;*.xlsx)|*.xls;*.xlsx|所有文件|*.*";ofd.ValidateNames true;ofd.CheckPathExists true;ofd.CheckFileExists true;if (ofd.ShowDialog() DialogResult.O…

ZOJ 2112 Dynamic Rankings

这里是题目地址 其实就是带修改的区间第K大。 写了一下BIT套主席树&#xff0c;内存飞起&#xff0c;似乎需要特别的优化技巧 所以还是写了一下线段树套平衡树&#xff0c;跑了1s左右。 其实线段树套平衡树就是归并树的自然扩展而已。 归并树是把归并排序的过程建成一颗线段树…

python3[进阶]8.对象引用、可变性和垃圾回收

文章目录8.1变量不是盒子8.2 标识,相等性和别名8.2.1 在和is之间选择8.2.2 元组的相对不可变性8.3 默认做浅复制&#xff08;拓展&#xff09;为任意对象做深复制和浅复制深拷贝和浅拷贝有什么具体的区别呢&#xff1f;8.4 函数的参数作为引用时8.4.1 不要使用可变类型作为参数…

python (第八章)补充-可迭代对象(补充高阶函数,以及常用的高阶函数)

文章目录可迭代对象迭代器什么是迭代器什么是生成器生成器的作用生成器的注意事项总结&#xff1a;高阶函数什么是高阶函数&#xff1f;map()函数filter()函数reduce()函数参考可迭代对象 我们已经知道&#xff0c;可以直接作用于for循环的数据类型有以下几种&#xff1a; 一类…

网络阅读开篇

网络阅读也符合马太效应&#xff0c;投入的时间越多&#xff0c;获取的有效信息却越来越少&#xff0c;因此做出以下规定&#xff1a; 1、限制网络阅读时间&#xff1b; 2、每次阅读做总结。 本来想的挺简单的&#xff0c;随便搜了一下&#xff0c;居然一部小心拜读了两位大神的…

python (第二章)数据结构

文章目录2.5 对序列使用 和 建立由列表组成的列表2.6序列的增量赋值&#xff08;和&#xff09;关于 的谜题补充&#xff1a;extend()方法和有什么区别呢&#xff1f;2.7 list.sort方法和内置函数sorted(排序)2.8 用bisect来管理已排序的序列2.8.2用bisect.insort插入元素2.9 当…

[Windows Phone] 实作不同的地图显示模式

[Windows Phone] 实作不同的地图显示模式 原文:[Windows Phone] 实作不同的地图显示模式前言 本文章主要示范如何让地图有不同的模式产生&#xff0c;例如平面图、地形图、鸟瞰图、鸟瞰图含街道等。 这部分主要是调整 Map.CartographicMode 属性&#xff0c;其中 MapCartograph…

[STemWin教程入门篇]第一期:emWin介绍

特别说明&#xff1a;原创教程&#xff0c;未经许可禁止转载&#xff0c;教程采用回复可见的形式&#xff0c;谢谢大家的支持。 armfly-x2,x3,v2,v3,v5开发板裸机和带系统的emWin工程已经全部建立&#xff0c;链接如下&#xff1a; http://bbs.armfly.com/read.php?tid1830 SE…

python 栈【测试题】

文章目录1.删除最外层的括号信息要求答案2.棒球比赛信息示例答案3. 用栈实现队列要求说明:答案4.用队列模拟栈描述注意答案5.下一个更大的元素&#xff08;未解&#xff09;信息&#xff1a;示例&#xff1a;注意:答案&#xff1a;6.删除字符串中的所有相邻重复项信息示例&…

python进阶(第三章1) 字典

文章目录3.1 泛映射类型什么是可散列的数据类型&#xff08;键的要求&#xff09;字典的构造方法3.2 字典推导(dictcomp)3.3 常见的映射方法用setdefault处理找不到的键3.4 映射的弹性键查询3.4.1 defaultdict:处理找不到的键的一个选择注意&#xff1a;defaultdict与dict实例化…

python基础 list和tuple

文章目录一、list1、len()函数可以获得list元素的个数2、索引从0开始3、末尾追加 append(xx)4、也可以把元素插入到指定的位置&#xff0c;比如索引号为1的位置(insert)5、末尾删除pop() &#xff0c;并且返回该值6、要删除指定位置的元素&#xff0c;用pop(i)方法&#xff0c;…

python基础 dict和set

文章目录dictset4.用集合为列表去重5.集合的增 add,update6.集合的删 discard,remove,pop,clear7 集合运算7.1 子集(<或者issubset()方法)7.2并集(|或者union()方法)7.3 交集(&或者intersection())7.4 差集(-或者difference()方法)7.5 对称集(^或者symmetric_difference…

python进阶(第三章2)字典和集合

文章目录3.8 集合论nee中的元素在haystack中出现的次数&#xff0c;可以在任何可迭代对象上3.8.1集合字面量3.8.2 集合推导3.8.3 集合操作3.9 dict和set的背后3.9.1 一个关于效率的实验3.9.2 字典中的散列表1.散列值和相等性2.散列表算法获取值&#xff1a;添加新的元素更新现有…

Android下实现GPS定位服务

1.申请Google API Key&#xff0c;参考前面文章 2.实现GPS的功能需要使用模拟器进行经纬度的模拟设置&#xff0c;请参考前一篇文章进行设置 3.创建一个Build Target为Google APIs的项目 4.修改Androidmanifest文件&#xff1a; view plain<uses-library android:name"…

DEDECMS全版本gotopage变量XSS ROOTKIT 0DAY

影响版本&#xff1a; DEDECMS全版本 漏洞描叙&#xff1a; DEDECMS后台登陆模板中的gotopage变量未效验传入数据&#xff0c;导致XSS漏洞。 \dede\templets\login.htm 65行左右 <input type"hidden" name"gotopage" value"<?php if(!empty($g…