Click here to Skip to main content
Email Password   helpLost your password?

Software Architecture Interview Questions Part 1 - Design Pattern Interview Questions

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 on http://www.questpond.com/FreeDesign1.htm . You can visit http://www.questpond.com and download the complete architecture interview questions PDF which covers SOA , UML , Design patterns , Togaf , OOPs etc.

You can read my other sections of the same in the below links :-

You can download the software architecture interview questions PDF

Download Software Architecture Interview Questions

Happy job hunting......

(B) 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.

(I) 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 remembering 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.

(A) Can you explain factory pattern?





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.

InterfaceAndConcrete.jpg

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

(I)Can you explain builder pattern?



Builder falls under the type of creational pattern category. Builder pattern helps us to separate the construction of a complex object from its representation so that the same construction process can create different representations. Builder pattern is useful when the construction of the object is very complex. The main objective is to separate the construction of objects and their representations. If we are able to separate the construction and representation, we can then get many representations from the same construction.

Figure: - Builder concept


To understand what we mean by construction and representation lets take the example of the below ‘Tea preparation’ sequence.

You can see from the figure ‘Tea preparation’ from the same preparation steps we can get three representation of tea’s (i.e. Tea with out sugar, tea with sugar / milk and tea with out milk).

Figure: - Tea preparation


Now let’s take a real time example in software world to see how builder can separate the complex creation and its representation. Consider we have application where we need the same report to be displayed in either ‘PDF’ or ‘EXCEL’ format. Figure ‘Request a report’ shows the series of steps to achieve the same. Depending on report type a new report is created, report type is set, headers and footers of the report are set and finally we get the report for display.

Figure: - Request a report

Now let’s take a different view of the problem as shown in figure ‘Different View’. The same flow defined in ‘Request a report’ is now analyzed in representations and common construction. The construction process is same for both the types of reports but they result in different representations.

Figure: - Different View


We will take the same report problem and try to solve the same using builder patterns. There are three main parts when you want to implement builder patterns.

Builder: - Builder is responsible for defining the construction process for individual parts. Builder has those individual processes to initialize and configure the product.
Director: - Director takes those individual processes from the builder and defines the sequence to build the product.
Product: - Product is the final object which is produced from the builder and director coordination.

First let’s have a look at the builder class hierarchy. We have a abstract class called as ‘ReportBuilder’ from which custom builders like ‘ReportPDF’ builder and ‘ReportEXCEL’ builder will be built.

Figure: - Builder class hierarchy

Figure ‘Builder classes in actual code’ shows the methods of the classes. To generate report we need to first Create a new report, set the report type (to EXCEL or PDF) , set report headers , set the report footers and finally get the report. We have defined two custom builders one for ‘PDF’ (ReportPDF) and other for ‘EXCEL’ (ReportExcel). These two custom builders define there own process according to the report type.

Figure: - Builder classes in actual code

Now let’s understand how director will work. Class ‘clsDirector’ takes the builder and calls the individual method process in a sequential manner. So director is like a driver who takes all the individual processes and calls them in sequential manner to generate the final product, which is the report in this case. Figure ‘Director in action’ shows how the method ‘MakeReport’ calls the individual process to generate the report product by PDF or EXCEL.


Figure: - Director in action

The third component in the builder is the product which is nothing but the report class in this case.

Figure: - The report class

Now let’s take a top view of the builder project. Figure ‘Client,builder,director and product’ shows how they work to achieve the builder pattern. Client creates the object of the director class and passes the appropriate builder to initialize the product. Depending on the builder the product is initialized/created and finally sent to the client.

Figure: - Client, builder, director and product

The output is something like this. We can see two report types displayed with their headers according to the builder.

Figure: - Final output of builder


Note :- In CD we have provided the above code in C# in ‘BuilderPattern’ folder.

(I) Can you explain prototype pattern?

Prototype pattern falls in the section of creational pattern. It gives us a way to create new objects from the existing instance of the object. In one sentence we clone the existing object with its data. By cloning any changes to the cloned object does not affect the original object value. If you are thinking by just setting objects we can get a clone then you have mistaken it. By setting one object to other object we set the reference of object BYREF. So changing the new object also changed the original object. To understand the BYREF fundamental more clearly consider the figure ‘BYREF’ below. Following is the sequence of the below code:

Figure :- BYREf

The conclusion of the above example is that objects when set to other objects are set BYREF. So changing new object values also changes the old object value.

There are many instances when we want the new copy object changes should not affect the old object. The answer to this is prototype patterns.

Lets look how we can achieve the same using C#. In the below figure ‘Prototype in action’ we have the customer class ‘ClsCustomer’ which needs to be cloned. This can be achieved in C# my using the ‘MemberWiseClone’ method. In JAVA we have the ‘Clone’ method to achieve the same. In the same code we have also shown the client code. We have created two objects of the customer class ‘obj1’ and ‘obj2’. Any changes to ‘obj2’ will not affect ‘obj1’ as it’s a complete cloned copy.



Figure: - Prototype in action


Note :- You can get the above sample in the CD in ‘Prototype’ folder. In C# we use the ‘MemberWiseClone’ function while in JAVA we have the ‘Clone’ function to achieve the same.

(A) Can you explain shallow copy and deep copy in prototype patterns?

There are two types of cloning for prototype patterns. One is the shallow cloning which you have just read in the first question. In shallow copy only that object is cloned, any objects containing in that object is not cloned. For instance consider the figure ‘Deep cloning in action’ we have a customer class and we have an address class aggregated inside the customer class. ‘MemberWiseClone’ will only clone the customer class ‘ClsCustomer’ but not the ‘ClsAddress’ class. So we added the ‘MemberWiseClone’ function in the address class also. Now when we call the ‘getClone’ function we call the parent cloning function and also the child cloning function, which leads to cloning of the complete object. When the parent objects are cloned with their containing objects it’s called as deep cloning and when only the parent is clones its termed as shallow cloning.

Figure: - Deep cloning in action

(B) Can you explain singleton pattern?

There are situations in a project where we want only one instance of the object to be created and shared between the clients. No client can create an instance of the object from outside. There is only one instance of the class which is shared across the clients. Below are the steps to make a singleton pattern:-

1) Define the constructor as private.
2) Define the instances and methods as static.

Below is a code snippet of a singleton in C#. We have defined the constructor as private, defined all the instance and methods using the static keyword as shown in the below code snippet figure ‘Singleton in action’. The static keyword ensures that you only one instance of the object is created and you can all the methods of the class with out creating the object. As we have made the constructor private, we need to call the class directly.

Figure: - Singleton in action

Note :- In JAVA to create singleton classes we use the STATIC keyword , so its same as in C#. You can get a sample C# code for singleton in the ‘singleton’ folder.

(A) Can you explain command patterns?

Command pattern allows a request to exist as an object. Ok let’s understand what it means. Consider the figure ‘Menu and Commands’ we have different actions depending on which menu is clicked. So depending on which menu is clicked we have passed a string which will have the action text in the action string. Depending on the action string we will execute the action. The bad thing about the code is it has lot of ‘IF’ condition which makes the coding more cryptic.

Figure: - Menu and Commands

Command pattern moves the above action in to objects. These objects when executed actually execute the command.
As said previously every command is an object. We first prepare individual classes for every action i.e. exit, open, file and print. Al l the above actions are wrapped in to classes like Exit action is wrapped in ‘clsExecuteExit’ , open action is wrapped in ‘clsExecuteOpen’, print action is wrapped in ‘clsExecutePrint’ and so on. All these classes are inherited from a common interface ‘IExecute’.

Figure: - Objects and Command

Using all the action classes we can now make the invoker. The main work of invoker is to map the action with the classes which have the action.
So we have added all the actions in one collection i.e. the arraylist. We have exposed a method ‘getCommand’ which takes a string and gives back the abstract object ‘IExecute’. The client code is now neat and clean. All the ‘IF’ conditions are now moved to the ‘clsInvoker’ class.

Figure: - Invoker and the clean client

Note: - You can find a sample code for C# code in command pattern in ‘Command’ folder.

Other Interview question PDF's

.NET Interview Question PDF

You must Sign In to use this message board.
 
 
Per page   
 FirstPrevNext
GeneralGood Article
Sakshi Smriti
0:18 9 Mar '10  
Good article enjoyed reading it...

Please update the links at the top of the article for part 3 and 4 they point to 2; although I changed the URL as you have made a naming convention for them .. thanks.

# Part 3 - SoftArch3.aspx
# Part 4 - SoftArch4.aspx
GeneralExplanation of Abstract Factory Pattern
Achintya Jha
10:30 7 Mar '10  
Shiv,

I liked your article, but abstract pattern really needs a detailed explanation.

Thanks
GeneralCreating Singleton pattern in a clustered environment.
AAVikash
9:52 14 Jan '10  
Hi,

Thanks for the articles.

Lets say my application has been deployed on clustered environment. Then how would i create/use singleton pattern?

As singleton means single instance for one process???

Just Confused

Regards,
VS
GeneralRe: Creating Singleton pattern in a clustered environment.
Shivprasad koirala
17:05 14 Jan '10  
Singleton objects as such do not have the capability to support cluster environment , we need to write the logic for it.

Visit my 500 videos on WCF,WPF,WWF,Silverlight,UML design patters @ http://www.questpond.com

GeneralRe: Creating Singleton pattern in a clustered environment.
AAVikash
21:09 15 Jan '10  
Thanks for your answer...

Could you please provide more details on how to achieve this?

Thanks,
VS
GeneralNice article
Sougandh
11:25 11 Oct '09  
Sir, there is a minor correction, there is a mixup in the class diagram attached to [Figure: - Example for abstract factory]. The ClsFactoryText creates a ClsTextBox and ClsFactoryButton creates ClsButton.

Rest of the article is superb. Thanks a lot for the same.

Sougandh Pavithran

GeneralLinks to Parts II, III, IV point to the same article!
DEGT
1:08 13 Mar '09  
Please revise the links to the other parts of this series, apparently they all point to SoftArch2.aspx instead of the actual III, IV parts and so on.

http://www.PanamaSights.com/
http://www.coralys.com/
http://www.virtual-aviation.info/

GeneralVery good
Donsw
17:49 20 Jan '09  
This is a well written article. I have read other books on patterns and you really get to the point. excellent job. Big Grin
GeneralMessage Automatically Removed
TV Mogul
4:02 3 Jan '09  
Message Automatically Removed
GeneralRe: Total Crap Based on Invalid Assumptions
Shivprasad koirala
5:11 3 Jan '09  
Oooh So much hatred....Don't read it.

Footprints on the sand are not made by sitting at the shore.

GeneralRe: Total Crap Based on Invalid Assumptions
TV Mogul
12:38 3 Jan '09  
I decided to post a commnet on your article because I feel it is people like yourself who keep programmers supressed and subjugated by employers. By writing an article like this you lead programmers to believe that they should prepare for testing instead of telling employers they REFUSE to be tested.

In addition, your article is based on false assumptions that the testing process can discern what skills a programmer has and doesn't have which is not the case.

You are perpetuating an evil system that is demeaning and racially biased.

Sigh

www.StationBreak.net
TV Mogul

GeneralRe: Total Crap Based on Invalid Assumptions
Shivprasad koirala
18:34 3 Jan '09  
TV Mogul wrote:
demeaning and racially biased.

I just wanted to reply because you used the word racial.


My freind its a preparation material. When a person a joins a organization he needs to show his skills. For hardworking programmers who do not get time to read in tight dead line projects , i thought this is the way out. I have been working continously tight dead line projects and when i have some good oppurtunity in my way there is no way i get ready in a night.


TV Mogul wrote:
You are perpetuating an evil system that is demeaning

Its a revision material ( whats wrong in revising) and do not mistake it that i want to spread evil in IT field. I love programming and it feeds my family. I will never think spreading EVIL in this system which helps out my family.


TV Mogul wrote:
In addition, your article is based on false assumptions that the testing process can discern what skills a programmer has and doesn't have which is not the case.

I think i have not written any assumption anywhere that this is a testing process it a prepration material a revision material.

Thanks for your comments. But i will not reply as you have used the word RACIAL.

Footprints on the sand are not made by sitting at the shore.

GeneralQualify yourself Moghul to even comment
jesukadita
5:56 10 Dec '09  
Haaa i saw your article Moghul on dating sites and other non-sense things. Your articles do not stand anywhere near to shivprasad koirala's article. He has covered almost all design patterns and thats great. First qualify yourself to even post comments on articles written by microsoft MVP's.
GeneralMy vote of 1
TV Mogul
3:51 3 Jan '09  
this is the kind of crap we all had to put up with in high school and assumption that ability to program is linked to test perforamnce is invlaid
GeneralVery Useful Article [modified]
Ahmed R El Bohoty
7:38 14 Nov '08  
Very Useful Article ... but i have one questions about Builder Pattern ..why we need product class where director class construct the component of product and when i want to produce any product i will implement IBuilder interface and write the behavior of each component and pass the concrete Builder to director without need the product and i will produce also different representation , plz give me the benefit of product class and real world example if u can ?

Thanks in advance

Discover Other ....
http://www.islamHouse.com
modified on Friday, November 14, 2008 3:29 PM

General123 books marks baaah
sid8897870
10:01 25 Oct '08  
Great to see the popularity of this series...Great
GeneralNice breif article
Ahmed Siddiqui
6:30 20 Oct '08  
Great work!

you have enclosed the core of software engineering in such a brief simple presentable article

I hope professionals will seriously consider it, instead of just passing their job interviews

http://devshop.wordpress.com

GeneralMore Twaddle
pwasser
18:20 18 Sep '08  
For heavens sake stop pumping out this nonsense which will just be used as ammunition by dickhead interviewers.

Shut your textbook, sit down at your computer, get a creative idea and produce something usefull from which the world can benefit.

Peter Wasser

GeneralRe: More Twaddle
Shivprasad koirala
18:58 18 Sep '08  
Noted...

When i die i die programming

GeneralRe: More Twaddle
sujonArch
19:49 3 Oct '08  
I really do not understand some people. when some body is doing constructive things what itches them. I am myself 10 yrs of experience whats wrong in having interview questions which can revise you quickly. Second this Mr pwasser has not written any articles. He just keeps posting messages to articles and bullshitting every one.

Looks like some people are habituated. Do you think Mr Koirala you should reply to these guys. You replying to him is like degrading yourself. Suggestions for you Put more source code rather than images. keep your article writing in the same pace great work...
GeneralRe: More Twaddle
pwasser
1:27 4 Oct '08  
A superb own goal.

Peter Wasser

GeneralUseless knowledge for theorists
Member 3082487
5:34 3 Sep '08  
I always astonished with you, guys, running around with those 'patterns'. Don't you really think all these 'Decorators/Visitors' will help you on a specific task? If program exists, it's already solved. If not, your patterns just blind you from fresh vision of stuff. Moreover: spending time (3x times related to 'stupid, obvious' solution) you can easy find that it was wrong pattern.
And most funny stuff is you look like a children who cannot eat ice-cream, because your 'patterns' has only pattern for eating semolina.
Every normal engineer must have bright mind to solve task 'on the fly', without remembering that 'academic solutions' like a GoF.
Well, if it's your business - no problem, make money. But please don't imagine from those pattern something like 'important knowledge'.
GeneralRe: Useless knowledge for theorists
Steven A. Lowe
9:03 8 Sep '08  
for many of us OO veterans, the GoF Design Patterns book was like reading our own development notes - they put good names and clear descriptions on things we had consciously or subconsciously invented years ago and now used as routinely as a loop

the Visitor pattern, for example, is pretty much unavoidable when working with graphs - it lurks beneath the surface of all graph algorithms (depth-first traversal, topological sorting, etc) as the common functional factor, i.e. every graph-traversal algorithm must "visit" the nodes in the graph and do something; the Visitor pattern makes this commonality explicit. Implementations of the Visitor pattern can allow for basically the same code to be reused in several different traversal contexts.

for people newer to OO, the GoF book is a step up to thinking at the next level, i.e. thinking in terms of reusable/recurring patterns of object interactions, instead of just reusable code/algorithms

so i respectfully disagree, this theory is useful knowledge

[but you stil have to know how to code a loop of course]

Best regards,
Steven A. Lowe
CEO, Innovator LLC
www.nov8r.com

GeneralRe: Useless knowledge for theorists
Shivprasad koirala
6:18 16 Sep '08  
I bow down and agree to you guys....
But i will still write these kind of articles...Many benefit...Many get jobs and i think thats bigger than anything

When i die i die programming

GeneralRe: Useless knowledge for theorists
Steven A. Lowe
6:51 16 Sep '08  
if you believe in what you're doing, stand your ground. I think that design patterns have definite merit, but of course that's not all there is to being a software architect Wink

good luck!

Best regards,
Steven A. Lowe
CEO, Innovator LLC
www.nov8r.com


Last Updated 3 Jan 2009 | Advertise | Privacy | Terms of Use | Copyright © CodeProject, 1999-2010