CODEDIGEST
Home » Articles
Search
 

Technologies
 

Sponsored links
 

CodeDigest Navigation
 

Technology News
No News Feeds available at this time.
 

Community News
No News Feeds available at this time.
 
Design Patterns Interview Questions - Part 1

By Shivprasad Koirala
Posted On Aug 12,2008
Article Rating:
Be first to rate
this article.
No of Comments: 2
Category: ASP.Net
Print this article.

Design Pattern Interview Questions – Part 1

Factory and Abstract factory

 

Introduction

 

Hi friends, Please 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.

 

To give you a practical understanding i have put all these design patterns in a video format and uploaded here. You can visit questpond.com  and download the complete architecture interview questions PDF which covers SOA , UML , Design patterns , Togaf , OOPs etc.


What are design patterns?

Design patterns are documented tried and tested solutions for recurring problems in a given context. So basically you have a problem context and the proposed solution for the same. Design patterns existed in some or other form right from the inception stage of software development. Let’s say if you want to implement a sorting algorithm the first thing comes to mind is bubble sort. So the problem is sorting and solution is bubble sort. Same holds true for design patterns.

 

Which are the three main categories of design patterns?

There are three basic classifications of patterns Creational, Structural, and Behavioral patterns.

Creational Patterns

·    Abstract Factory:- Creates an instance of several families of classes

·    Builder: - Separates object construction from its representation

·    Factory Method:- Creates an instance of several derived classes

·    Prototype:- A fully initialized instance to be copied or cloned

·    Singleton:- A class in which only a single instance can exist

Note: - The best way to remember Creational pattern is by ABFPS (Abraham Became First President of States).

Structural Patterns

·     Adapter:-Match interfaces of different classes.

·     Bridge:-Separates an object’s abstraction from its implementation.

·     Composite:-A tree structure of simple and composite objects.

·     Decorator:-Add responsibilities to objects dynamically.

·     Façade:-A single class that represents an entire subsystem.

·     Flyweight:-A fine-grained instance used for efficient sharing.

·     Proxy:-An object representing another object.

Note : To remember structural pattern best is (ABCDFFP)

Behavioral Patterns

·       Mediator:-Defines simplified communication between classes.

·       Memento:-Capture and restore an object's internal state.

·       Interpreter:- A way to include language elements in a program.

·      Iterator:-Sequentially access the elements of a collection.

·       Chain of Resp: - A way of passing a request between a chain of objects.

·       Command:-Encapsulate a command request as an object.

·       State:-Alter an object's behavior when its state changes.

·       Strategy:-Encapsulates an algorithm inside a class.

·       Observer: - A way of notifying change to a number of classes.

·       Template Method:-Defer the exact steps of an algorithm to a subclass.

·      Visitor:-Defines a new operation to a class without change.

Note: - Just remember Music....... 2 MICS On TV (MMIICCSSOTV).

 

Note :- In the further section we will be covering all the above design patterns in a more detail manner.

 

Can you explain factory pattern?

Factory pattern is one of the types of creational patterns. You can make out from the name factory itself it’s meant to construct and create something. In software architecture world factory pattern is meant to centralize creation of objects.  Below is a code snippet of a client which has different types of invoices. These invoices are created depending on the invoice type specified by the client. There are two issues with the code below:-

Ø       First we have lots of ‘new’ keyword scattered in the client. In other ways the client is loaded with lot of object creational activities which can make the client logic very complicated.

Ø       Second issue is that the client needs to be aware of all types of invoices. So if we are adding one more invoice class type called as ‘InvoiceWithFooter’ we need to reference the new class in the client and recompile the client also.

 

 

Figure: - Different types of invoice

Taking these issues as our base we will now look in to how factory pattern can help us solve the same. Below figure ‘Factory Pattern’ shows two concrete classes ‘ClsInvoiceWithHeader’ and ‘ClsInvoiceWithOutHeader’. 

 

The first issue was that these classes are in direct contact with client which leads to lot of ‘new’ keyword scattered in the client code. This is removed by introducing a new class ‘ClsFactoryInvoice’ which does all the creation of objects.

 

The second issue was that the client code is aware of both the concrete classes i.e. ‘ClsInvoiceWithHeader’ and ‘ClsInvoiceWithOutHeader’. This leads to recompiling of the client code when we add new invoice types. For instance if we add ‘ClsInvoiceWithFooter’ client code needs to be changed and recompiled accordingly. To remove this issue we have introduced a common interface ‘IInvoice’. Both the concrete classes ‘ClsInvoiceWithHeader’ and ‘ClsInvoiceWithOutHeader’ inherit and implement the ‘IInvoice’ interface.

 

The client references only the ‘IInvoice’ interface which results in zero connection between client and the concrete classes ( ‘ClsInvoiceWithHeader’ and ‘ClsInvoiceWithOutHeader’).  So now if we add new concrete invoice class we do not need to change any thing at the client side.

 

In one line the creation of objects is taken care by ‘ClsFactoryInvoice’ and the client disconnection from the concrete classes is taken care by ‘IInvoice’ interface.

 

Figure: - Factory pattern

Below are the code snippets of how actually factory pattern can be implemented in C#. In order to avoid recompiling the client we have introduced the invoice interface ‘IInvoice’. Both the concrete classes ‘ClsInvoiceWithOutHeaders’ and ‘ClsInvoiceWithHeader’ inherit and implement the ‘IInvoice’ interface.

Figure :- Interface and concrete classes

 

We have also introduced an extra class ‘ClsFactoryInvoice’ with a function ‘getInvoice()’ which will generate objects of both the invoices depending on ‘intInvoiceType’ value. In short we have centralized the logic of object creation in the ‘ClsFactoryInvoice’. The client calls the ‘getInvoice’ function to generate the invoice classes. One of the most important points to be noted is that client only refers to ‘IInvoice’ type and the factory class ‘ClsFactoryInvoice’ also gives the same type of reference. This helps the client to be complete detached from the concrete classes,  so now when we add new classes and invoice types we do not need to recompile the client.




 

 

Figure: - Factory class which generates objects

 

Note :- The above example is given in C# . Even if you are from some other technology you can still map the concept accordingly. You can get source code from the CD in ‘FactoryPattern’ folder.

 

(I) Can you explain abstract factory pattern?

Abstract factory expands on the basic factory pattern. Abstract factory helps us to unite similar factory pattern classes in to one unified interface. So basically all the common factory patterns now inherit from a common abstract factory class which unifies them in a common class. All other things related to factory pattern remain same as discussed in the previous question.

 

A factory class helps us to centralize the creation of classes and types. Abstract factory helps us to bring uniformity between related factory patterns which leads more simplified interface for the client.

 

Figure: - Abstract factory unifies related factory patterns

 

Now that we know the basic lets try to understand the details of how abstract factory patterns are actually implemented. As said previously we have the factory pattern classes (factory1 and factory2) tied up to a common abstract factory (AbstractFactory Interface) via inheritance. Factory classes stand on the top of concrete classes which are again derived from common interface. For instance in figure ‘Implementation of abstract factory’ both the concrete classes ‘product1’ and ‘product2’ inherits from one interface i.e. ‘common’. The client who wants to use the concrete class will only interact with the abstract factory and the common interface from which the concrete classes inherit.

 

Figure: - Implementation of abstract factory

Now let’s have a look at how we can practically implement abstract factory in actual code. We have scenario where we have UI creational activities for textboxes and buttons through their own centralized factory classes ‘ClsFactoryButton’ and ‘ClsFactoryText’. Both these classes inherit from common interface ‘InterfaceRender’. Both the factories ‘ClsFactoryButton’ and ‘ClsFactoryText’ inherits from the common factory ‘ClsAbstractFactory’. Figure ‘Example for  AbstractFactory’ shows how these classes are arranged and the client code for the same. One of the important points to be noted about the client code is that it does not interact with the concrete classes. For object creation it uses the abstract factory ( ClsAbstractFactory ) and for  calling the concrete class implementation it calls the methods via the interface ‘InterfaceRender’. So the ‘ClsAbstractFactory’ class provides a common interface for both factories ‘ClsFactoryButton’ and ‘ClsFactoryText’.

 

Figure: - Example for abstract factory

 

Note: - We have provided a code sample in C# in the ‘AbstractFactory’ folder. People who are from different technology can compare easily the implementation in their own language.

We will just run through the sample code for abstract factory. Below code snippet ‘Abstract factory and factory code snippet’ shows how the factory pattern classes inherit from abstract factory.

 

 

Figure: - Abstract factory and factory code snippet

Figure ‘Common Interface for concrete classes’  how the concrete classes inherits from a common interface ‘InterFaceRender’ which enforces the method ‘render’ in all the concrete classes.

 

Figure: - Common interface for concrete classes

The final thing is the client code which uses the interface ‘InterfaceRender’ and abstract factory ‘ClsAbstractFactory’ to call and create the objects. One of the important points about the code is that it is completely isolated from the concrete classes. Due to this any changes in concrete classes like adding and removing concrete classes does not need client level changes.

Figure: - Client, interface and abstract factory

 

Conclusion

Thus, Part 1 of this article we have understood the basics of design patterns and types of design patterns. This part also discussed factory pattern in detail with example. Moving forward, we will see about other patterns in this article series. Stay tuned!!

Thanks for reading my article!

Please post your queries and doubts in article feedback section.

Similar Articles
You can contribute to CodeDiget.Com:
Donate to CodeDigest.com
Article Feedback
Comments
Design Patterns
Very nice doc about Factory and Abstract Factory Patterns.
It was really confusing for me, but this doc explained it very nicely. I would recomend this for anybody who is new to design patterns. Explained in a very simple manner and easily understandable.
Thanks for this post.
Desgin Patterns
Hi Shiv, Very impressinve article which helps me to start explore on design patterns more. hoping to see more on design patterns from you. My Question on Factory Method: You discussed abt the two issues in the client code which directly interact with concrete classes. Could you tell me more about the consequences of these two issues?