[转]Design Pattern Interview Questions - Part 3
- (I) Can you explain state pattern?
- (I) Can you explain strategy pattern?
- (A) Can you explain visitor pattern?
- (A) What the difference between visitor and strategy pattern?
- (A) Can you explain adapter pattern?
- (I) What is fly weight pattern?
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 / answersvideos.
If you have not read my pervious section you can always read from below
- Design Pattern Interview Questions Part 1
- Design Pattern Interview Questions Part 2
- Design Pattern Interview Questions Part 4
- UML Part 1 Interview questions UML Part 1
- UML Part 2 interview questions UML Part 2
Happy job hunting......
(I) Can you explain state pattern?
State pattern allows an object to change its behavior depending on the current values of the object. Consider the figure ‘State pattern example’. It’s an example of a bulb operation. If the state of the bulb is off and you press the switch the bulb will turn off. If the state of bulb is on and you press the switch the bulb will be off. So in short depending on the state the behavior changes.

Figure: - State pattern example
Now let’s try to implement the same bulb sample in C#. Figure ‘State pattern in action’ shows both the class and the client code. We have made a class called as ‘clsState’ which has an enum with two state constants ‘On’ and ‘Off’. We have defined a method ‘PressSwitch’ which toggles its state depending on the current state. In the right hand side of the same figure we have defined a client which consumes the ‘clsState’ class and calls the ‘PressSwitch()’ method. We have displayed the current status on the textbox using the ‘getStatus’ function.
When we click the press switch it toggles to the opposite state of what we have currently.

Figure: - State pattern in action
(I) Can you explain strategy pattern?
Strategy pattern are algorithms inside a class which can be interchanged depending on the class used. This pattern is useful when you want to decide on runtime which algorithm to be used.
Let’s try to see an example of how strategy pattern works practically. Let’s take an example of a math’s calculation where we have strategies like add and substract. Figure ‘Strategy in action’ shows the same in a pictorial format. It takes two numbers and the depending on the strategy it gives out results. So if it’s an addition strategy it will add the numbers, if it’s a substraction strategy it will give the substracted results. These strategies are nothing but algorithms. Strategy pattern are nothing but encapsulation of algorithms inside classes.

Figure: - Strategy in action
So the first thing we need to look in to is how these algorithms can be encapsulated inside the classes. Below figure ‘Algorithm encapsulated’ shows how the ‘add’ is encapsulated in the ‘clsAddStatergy’ class and ‘substract’ in the ‘clsSubstractStatergy’ class. Both these classes inherit from ‘clsStratergy’ defining a ‘calculate’ method for its child classes.

Figure: - Algorithms encapsulated
Now we define a wrapper class called as ‘clsMaths’ which has a reference to the ‘clsStatergy’ class. This class has a ‘setStatergy’ method which sets the strategy to be used.

Figure: - Strategy and the wrapper class
Below figure ‘Strategy client code’ shows how the wrapper class is used and the strategy object is set on runtime using the ‘setStatergy’ method.

Figure: - Strategy client code
(A) Can you explain visitor pattern?
Visitor pattern allows us to change the class structure with out changing the actual class. Its way of separating the logic and algorithm from the current data structure. Due to this you can add new logic to the current data structure with out altering the structure. Second you can alter the structure with out touching the logic.
Consider the below figure ‘Logic and data structure’ where we have a customer data structure. Every customer object has multiple address objects and every address object had multiple phone objects. This data structure needs to be displayed in two different formats one is simple string and second XML. So we have written two classes one is the string logic class and other is the XML logic class. These two classes traverse through the object structure and give the respective outputs. In short the visitor contains the logic.

Figure: - Logic and data structure
Let’s take the above customer sample and try to implement the same in C#. If you are from other programming you should be able to map the same accordingly. We have created two visitor classes one which will be used to parse for the string logic and other for XML. Both these classes have a visit method which takes each object and parses them accordingly. In order to maintain consistency we have implemented them from a common interface ‘IVisitor’.

Figure :- Visitor class
The above defined visitor class will be passed to the data structure class i.e. the customer class. So in the customer class we have passed the visitor class in an ‘Accept’ function. In the same function we pass this class type and call the visit function. The visit function is overloaded so it will call according to the class type passed.

Figure: - Visitor passed to data structure class
Now every customer has multiple address objects and every address has multiple phone objects. So we have ‘objAddresses’ arraylist object aggregated in the ‘clsCustomer’ class and ‘objPhones’ arraylist aggregated in the ‘clsAddress’ class. Every object has the accept method which takes the visitor class and passes himself in the visit function of the visitor class. As the visit function of the visitor class is overloaded it will call the appropriate visitor method as per polymorphism.

Figure: - Customer, Address and phones
Now that we have the logic in the visitor classes and data structure in the customer classes its
time to use the same in the client. Below figure ‘Visitor client code’ shows a sample code snippet for using the visitor pattern. So we create the visitor object and pass it to the customer data class. If we want to display the customer object structure in a string format we create the ‘clsVisitorString’ and if we want to generate in XML format we create the ‘clsXML’ object and pass the same to the customer object data structure. You can easily see how the logic is now separated from the data structure.

Figure: - Visitor client code
Note: - You can find a sample of the same in C# in the visitor folder of the CD. If you belong to some other programming domain you can map the same as the code is very generic.
(A) What the difference between visitor and strategy pattern?
Visitor and strategy look very much similar as they deal with encapsulating complex logic from data. We can say visitor is more general form of strategy.
In strategy we have one context or a single logical data on which multiple algorithms operate. In the previous questions we have explained the fundamentals of strategy and visitor. So let’s understand the same by using examples which we have understood previously. In strategy we have a single context and multiple algorithms work on it. Figure ‘Strategy’ shows how we have a one data context and multiple algorithm work on it.

Figure: - Strategy
In visitor we have multiple contexts and for every context we have an algorithm. If you remember the visitor example we had written parsing logic for every data context i.e. customer, address and phones object.

Figure: - Visitor
So in short strategy is a special kind of visitor. In strategy we have one data context and multiple algorithms while in visitor for every data context we have one algorithm associated. The basic criteria of choosing whether to implement strategy or visitor depends on the relationship between context and algorithm. If there is one context and multiple algorithms then we go for strategy. If we have multiple contexts and multiple algorithms then we implement visitor algorithm.
(A) Can you explain adapter pattern?
Many times two classes are incompatible because of incompatible interfaces. Adapter helps us to wrap a class around the existing class and make the classes compatible with each other. Consider the below figure ‘Incompatible interfaces’ both of them are collections to hold string values. Both of them have a method which helps us to add string in to the collection. One of the methods is named as ‘Add’ and the other as ‘Push’. One of them uses the collection object and the other the stack. We want to make the stack object compatible with the collection object.

Figure: - Incompatible interfaces
There are two way of implementing adapter pattern one is by using aggregation (this is termed as the object adapter pattern) and the other inheritance (this is termed as the class adapter pattern). First let’s try to cover object adapter pattern.
Figure ‘Object Adapter pattern’ shows a broader view of how we can achieve the same. We have a introduced a new wrapper class ‘clsCollectionAdapter’ which wraps on the top of the ‘clsStack’ class and aggregates the ‘push’ method inside a new ‘Add’ method, thus making both the classes compatible.

Figure: - Object Adapter pattern
The other way to implement the adapter pattern is by using inheritance also termed as class adapter pattern. Figure ‘Class adapter pattern’ shows how we have inherited the ‘clsStack’ class in the ‘clsCollectionAdapter’ and made it compatible with the ‘clsCollection’ class.

Figure :- Class adapter pattern
Note :- You can the above C# example in the adapter folder of the CD.
(I) What is fly weight pattern?
Fly weight pattern is useful where we need to create many objects and all these objects share some kind of common data. Consider figure ‘Objects and common data’. We need to print visiting card for all employees in the organization. So we have two parts of data one is the variable data i.e. the employee name and the other is static data i.e. address. We can minimize memory by just keeping one copy of the static data and referencing the same data in all objects of variable data. So we create different copies of variable data, but reference the same copy of static data. With this we can optimally use the memory.

Figure: - Objects and common data
Below is a sample C# code demonstration of how flyweight can be implemented practically. We have two classes, ‘clsVariableAddress’ which has the variable data and second ‘clsAddress’ which has the static data. To ensure that we have only one instance of ‘clsAddress’ we have made a wrapper class ‘clsStatic’ and created a static instance of the ‘clsAddress’ class. This object is aggregated in the ‘clsVariableAddress’ class.

Figure: - Class view of flyweight
Figure ‘Fly weight client code’ shows we have created two objects of ‘clsVariableAddress’ class, but internally the static data i.e. the address is referred to only one instance.

Figure: - Fly weight client code
[转]Design Pattern Interview Questions - Part 3的更多相关文章
- [转]Design Pattern Interview Questions - Part 2
Interpeter , Iterator , Mediator , Memento and Observer design patterns. (I) what is Interpreter pat ...
- [转]Design Pattern Interview Questions - Part 1
Factory, Abstract factory, prototype pattern (B) What are design patterns? (A) Can you explain facto ...
- [转]Design Pattern Interview Questions - Part 4
Bridge Pattern, Composite Pattern, Decorator Pattern, Facade Pattern, COR Pattern, Proxy Pattern, te ...
- 115 Java Interview Questions and Answers – The ULTIMATE List--reference
In this tutorial we will discuss about different types of questions that can be used in a Java inter ...
- What Great .NET Developers Ought To Know (More .NET Interview Questions)
A while back, I posted a list of ASP.NET Interview Questions. Conventional wisdom was split, with ab ...
- Top 25 Most Frequently Asked Interview Core Java Interview Questions And Answers
We are sharing 25 java interview questions , these questions are frequently asked by the recruiters. ...
- 69 Spring Interview Questions and Answers – The ULTIMATE List--reference
This is a summary of some of the most important questions concerning the Spring Framework, that you ...
- Verilog Tips and Interview Questions
Verilog Interiew Quetions Collection : What is the difference between $display and $monitor and $wr ...
- Popular HashMap and ConcurrentHashMap Interview Questions
http://howtodoinjava.com/core-java/collections/popular-hashmap-and-concurrenthashmap-interview-quest ...
随机推荐
- OpenNURBS 3DM Viewer
OpenNURBS 3DM Viewer eryar@163.com Abstract. The openNURBS Toolkit consists of C++ source code for a ...
- 为 Neutron 准备物理基础设施(I) - 每天5分钟玩转 OpenStack(75)
前面讨论了 Neutron 的架构和基础知识,接下来就要通过实验深入学习和实践了. 第一步就是准备实验用的物理环境,考虑如下几个问题: 需要几个节点? 如何分配节点的角色? 节点上部署哪些服务? 配几 ...
- 应用程序框架实战二十二 : DDD分层架构之仓储(层超类型基础篇)
前一篇介绍了仓储的基本概念,并谈了我对仓储的一些认识,本文将实现仓储的基本功能. 仓储代表聚合在内存中的集合,所以仓储的接口需要模拟得像一个集合.仓储中有很多操作都是可以通用的,可以把这部分操作抽取到 ...
- canvas学习笔记
html5的新标签:canvas; 作用:标签定义图形,比如图表和其他图像:标签只是图形容器,您必须使用脚本来绘制图形.默认大小:宽300px,高150px; 背景知识:概念最初由苹果公司提出的,用于 ...
- swift 中指针的使用UnsafeMutablePointer
在swift中已经弱化了指针的使用,可以这么使用 let s: NSRange = NSMakeRange(, ) let at = UnsafeMutablePointer<NSRange&g ...
- 在非SQL客户端使用命令行方式定期连接SQL Server 服务器并模拟用户查询操作,同时输出信息内容
一个很长的标题,实现的功能就是尽量使用非人力的方式模拟人去做一件事情,为了便于记录,将他们输出成文件方便查阅. 图形界面方式,使用微软自己的ConnMaker.exe,或者Microsoft 数据连接 ...
- c 语言的位运算符复习
转载和修正,原文连接:http://www.cnblogs.com/911/archive/2008/05/20/1203477.html 位运算是指按二进制进行的运算.在系统软件中,常常需要处理二进 ...
- 关于BFC不会被浮动元素遮盖的一些解释
简介 在清除浮动一文中提到BFC不会被浮动元素遮盖,并没有详细探究表现行为.规范中指出,在同一个BFC内,作为子元素的BFC的border-box不应该覆盖同为子元素的浮动元素的margin-box. ...
- DatePickerDialog、AutoCompleteTextView
DatePickerDialog选择日期,调用showDialog(int id)方法,会执行onCreateDialog方法: @Override protected Dialog onCreate ...
- jquery 图片轮播demo实现
转载注明出处!!! 转载注明出处!!! 转载注明出处!!! 图片轮播demo,弄清楚过程其实是一个很简单的东西,看网上都没有什么实质性的代码,就自己把过程捋了一遍实现了. 这次因为随手写的,所以没有做 ...