0% found this document useful (0 votes)
242 views

Design Patterns

Factory pattern is one of the creational patterns that is used to centralize object creation. It solves issues like scattering of 'new' operator in client code and tight coupling between client and concrete classes. The factory pattern uses a factory interface to create objects without specifying the exact class. The client only communicates with the factory interface. Abstract factory pattern groups factories that have similar creation processes. It provides a common interface for creation of related or dependent objects. Builder pattern separates object construction from its representation, allowing the same construction steps to create different types of objects.

Uploaded by

dhirenthakur
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
242 views

Design Patterns

Factory pattern is one of the creational patterns that is used to centralize object creation. It solves issues like scattering of 'new' operator in client code and tight coupling between client and concrete classes. The factory pattern uses a factory interface to create objects without specifying the exact class. The client only communicates with the factory interface. Abstract factory pattern groups factories that have similar creation processes. It provides a common interface for creation of related or dependent objects. Builder pattern separates object construction from its representation, allowing the same construction steps to create different types of objects.

Uploaded by

dhirenthakur
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 115

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. Lets 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 remembering ABFPS (Abraham
Became First President of States).
Structural Patterns
Adapter:-Match interfaces of different classes .
Bridge:-Separates an objects abstraction from its implementation.
Composite:-A tree structure of simple and composite objects.
Decorator:-Add responsibilities to objects dynamically.
Faade:-A single class that represents an entire subsystem.
Flyweight:-A fine-grained instance used for efficient sharing.
Proxy:-An object representing another object.
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.

Can you explain factory pattern?

Factory pattern is one of the types of creational patterns. You can make out from the
name factory itself its 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

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 lets 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

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

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 teas (i.e. Tea with out sugar, tea with sugar / milk and tea with out
milk).

Figure: - Tea preparation


Now lets 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 lets 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 lets 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 lets 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 lets 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

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:

In the first step we have created the first object i.e. obj1 from class1.

In the second step we have created the second object i.e. obj2 from class1.

In the third step we set the values of the old object i.e. obj1 to old value.

In the fourth step we set the obj1 to obj2.

In the fifth step we change the obj2 value.

Now we display both the values and we have found that both the objects have the new
value.

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
its a complete cloned copy.

Figure: - Prototype in action

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 its called as deep cloning and when only the
parent is clones its termed as shallow cloning.

Figure: - Deep cloning in action

Can you explain singleton pattern?


Collapse | Copy Code
Punch :- Create a single instance of object and provides access to this
single instance via a central point.

There are situations in project where we want only one instance of the object to be created
and shared between the clients. For instance lets say we have the below two classes,
currency and country.
These classes load master data which will be referred again and again in project. We would
like to share a single instance of the class to get performance benefit by not hitting the
database again and again.
Collapse | Copy Code
public class Currency
{
List<string /> oCurrencies = new List<string />();
public Currency()
{
oCurrencies.Add("INR");
oCurrencies.Add("USD");
oCurrencies.Add("NEP");
oCurrencies.Add("GBP");

}
public IEnumerable<string /> getCurrencies()
{
return (IEnumerable<string />)oCurrencies;
}
}

Collapse | Copy Code

public class Country


{
List<string /> oCountries = new List<string />();
public Country()
{
oCountries.Add("India");
oCountries.Add("Nepal");
oCountries.Add("USA");
oCountries.Add("UK");
}
public IEnumerable<string /> getCounties()
{
return (IEnumerable<string />) oCountries;
}
}

Implementing singleton pattern is a 4 step process.


Step 1: - Create a sealed class with a private constructor
The private constructor is important so that clients cannot create object of the class directly. If
you remember the punch, the main intention of this pattern is to create a single instance of the
object which can be shared globally, so we do not want to give client the control to create
instances directly.
Collapse | Copy Code

public sealed class GlobalSingleton


{
private GlobalSingleton() { }
..
.
}

Step 2: - Create aggregated objects of the classes (for this example it is currency and
country) for which we want single instance.
Collapse | Copy Code
public sealed class GlobalSingleton
{
// object which needs to be shared globally
public Currency Currencies = new Currency();
public Country Countries = new Country();

Step 3: - Create a static read-only object of t he class itself and expose the same via
static property as shown below.

Collapse | Copy Code


public sealed class GlobalSingleton
{
.

// use static variable to create a single instance of the object


static readonly GlobalSingleton INSTANCE = new GlobalSingleton();
public static GlobalSingleton Instance
{
get
{
return INSTANCE;
}

Step 4: - You can now consume the singleton object using the below code from the client.
Collapse | Copy Code

GlobalSingleton oSingle = GlobalSingleton.Instance;


Country o = osingl1.Country;

Below goes the complete code for singleton pattern which we discussed above in pieces.
Collapse | Copy Code

public sealed class GlobalSingleton


{
// object which needs to be shared globally
public Currency Currencies = new Currency();
public Country Countries = new Country();
// use static variable to create a single instance of the object
static readonly GlobalSingleton INSTANCE = new GlobalSingleton();
/// This is a private constructor, meaning no outsides have access.
private GlobalSingleton()
{ }
public static GlobalSingleton Instance
{
get
{
return INSTANCE;
}

Can you explain command patterns?


Command pattern allows a request to exist as an object. Ok lets 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

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

Lets 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

Lets 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, lets 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


Can you explain iterator pattern?

Iterator pattern allows sequential access of elements with out exposing the inside code. Lets
understand what it means. Lets 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. Its 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


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

Lets consider the figure Mediator sample example which depicts a true scenario of the need
of mediator pattern. Its 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 UIs. 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 lets 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


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. Lets understand what it means in practical sense. Consider figure Memento
practical example, it shows a customer screen. Lets 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

Lets 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


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

Lets try to code the same example which we have defined in the previous section. First lets
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


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. Its 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 lets 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


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.
Lets try to see an example of how strategy pattern works practically. Lets take an example
of a maths 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 its an addition strategy it will add the numbers, if its 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


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

Lets 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


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 lets
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.
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 lets 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


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

Can you explain bridge pattern?


Bridge pattern helps to decouple abstraction from implementation. With this if the
implementation changes it does not affect abstraction and vice versa. Consider the figure
Abstraction and Implementation. The switch is the abstraction and the electronic
equipments are the implementations. The switch can be applied to any electronic equipment,
so the switch is an abstract thinking while the equipments are implementations.

Figure: - Abstraction and Implementation


Lets try to code the same switch and equipment example. First thing is we segregate the
implementation and abstraction in to two different classes. Figure Implementation shows
how we have made an interface IEquipment with Start() and Stop() methods. We have
implemented two equipments one is the refrigerator and the other is the bulb.

Figure :- Implementation
The second part is the abstraction. Switch is the abstraction in our example. It has a
SetEquipment method which sets the object. The On method calls the Start method of the
equipment and the off calls the stop.

Figure: - Abstraction
Finally we see the client code. You can see we have created the implementation objects and
the abstraction objects separately. We can use them in an isolated manner.

Figure :- Client code using bridge

Can you explain composite pattern?


Collapse | Copy Code

GOF definition :- A tree structure of simple and composite objects

Many times objects are organized in tree structure and developers have to understand the
difference between leaf and branch objects. This makes the code more complex and can lead
to errors.
For example below is a simple object tree structure where the customer is the main object
which has many address objects and every address object references lot of phone objects.

Figure: - General Process


Now lets say you want to insert the complete object tree. The sample code will be something
as shown below. The code loops through all the customers, all addresses inside the customer
object and all phones inside the address objects. While this loop happens the respective
update methods are called as shown in the below code snippet.
Collapse | Copy Code

foreach (Customer objCust in objCustomers)


{
objCust.UpDateCustomer();
foreach (Address oAdd in objCust.Addresses)
{
oAdd.UpdateAddress();
}
foreach (Phone ophone in oAdd.Phones)
{
ophone.UpDatePhone();
}
}

The problem with the above code is that the update vocabulary changes for each object. For
customer its UpdateCustomer , for address its UpdateAddress and for phone it is
UpdatePhone. In other words the main object and the contained leaf nodes are treated
differently. This can lead to confusion and make your application error prone.
The code can be cleaner and neat if we are able to treat the main and leaf object uniformly.
You can see in the below code we have created an interface (IBusinessObject) which forces
all the classes i.e. customer, address and phone to use a common interface. Due to the
common interface all the object now have the method name as Update.
Collapse | Copy Code

foreach (IBusinessObject ICust in objCustomers)

{
ICust.Update();
foreach (IBusinessObject Iaddress in ((Customer)(ICust)).ChildObjects)
{
Iaddress.Update();
foreach (IBusinessObject iphone in ((Address)(Iaddress)).ChildObjects)
{
iphone.Update();
}
}
}

In order to implement composite pattern first create an interface as shown in the below code
snippet.
Collapse | Copy Code

public interface IBusinessObject


{
void Update();
bool isValid();
void Add(object o);
}

Force this interface across all the root objects and leaf / node objects as shown below.
Collapse | Copy Code

public class Customer : IBusinessObject


{
private List<Address> _Addresses;
public IEnumerable<Address> ChildObjects
{
get
{
return (IEnumerable<Address>)_Addresses;
}
}
public void Add(object objAdd)
{
_Addresses.Add((Address) objAdd);
}
public void Update()
{

}
public bool isValid()
{
return true;
}

Force the implementation on the address object also.


Collapse | Copy Code
public class Address : IBusinessObject
{
private List<Phone> _Phones;

public IEnumerable<Phone> ChildObjects


{
get
{
return (IEnumerable<Phone>)_Phones.ToList<object>();
}
}
public void Add(object objPhone)
{
_Phones.Add((Phone)objPhone);
}

public void Update()


{
}
public bool isValid()
{
return true;
}
}

Force the implementation on the last node object i.e. phone.


Collapse | Copy Code
public class Phone : IBusinessObject
{
public void Update()
{}
public bool isValid()
{return true;}
public void Add(object o)
{
// no implementaton
}
}

Can you explain decorator pattern ?


Collapse | Copy Code

Punch :- Decorator pattern adds dynamically stacked behavior thus helping


us to change the behavior of the object on runtime.

There are situations where we would like to add dynamic stacked behavior to a class on
runtime. The word stack is an important word to note. For instance consider the below
situation where a hotel sells bread meals. They have four important products and the order
can be placed using the below combination:

Simple bread.

Bread with Chicken.

Bread with drinks

Bread with chicken and drinks.

In other words the order process behavior and the cost of the order changes on runtime
depending on the type of the combination.

Figure: Below is a simple order with only bread which has two functions prepare and
calculatecost. We would like to add new products to this basic bread order dynamically on
runtime depending on what the customer wants.
Below is a simple interface which every order will have i.e. Prepare and CalculateCost.
Collapse | Copy Code

interface IOrder
{
string Prepare();
double CalculateCost();

The base product is the bread which implements the Iorder interface. We would like to add
new products to the bread order and change the behavior of the complete order.
Collapse | Copy Code

public class OrderBread : IOrder


{
public string Prepare()
{
string strPrepare="";
strPrepare = "Bake the bread in oven\n";
strPrepare = strPrepare + "Serve the bread";
return strPrepare;
}

public double CalculateCost()


{
return 200.30;
}

We can alter the bread order dynamically using decorator pattern. To implement decorator
pattern is a 5 steps process.
Step1:- Create a decorator class which aggregates the object / interface for which we need to
add the behavior dynamically.
Collapse | Copy Code
abstract class OrderDecorator : IOrder
{
protected IOrder Order;
. . . . .
. . . . .
. . . . .
}

This decorator class will house the object and any method calls to the main object will first
invoke all the housed objects and then the main object.
So for instance if you are calling the prepare method, this decorator class will invoke all the
prepare methods of the housed object and then the final prepare method. You can see how the
output changes when decorator comes in to picture.

Figure: Step 2: - The housed object/ interface pointer needs to be initialized. We can do the same by
using various means for the sample below we will just expose a simple constructor and pass
the object to the constructor to initialize the housed object.
Collapse | Copy Code

abstract class OrderDecorator : IOrder


{
protected IOrder Order;
public OrderDecorator(IOrder oOrder)
{
Order = oOrder;
}
. . . . .
}

Step 3: - We will implement the Iorder interface and invoke the house object methods using
the virtual methods. You can see we have created virtual methods which invoke the house
object methods.

Collapse | Copy Code


abstract class OrderDecorator : IOrder
{
protected IOrder Order;
public OrderDecorator(IOrder oOrder)
{
Order = oOrder;
}
public virtual string Prepare()
{
return Order.Prepare();
}

public virtual double CalculateCost()


{
return Order.CalculateCost();
}

Step 4: - We are done with the important step i.e. creating the decorator. Now we need to
create dynamic behavior object which can be added to the decorator to change object
behavior on runtime.
Below is a simple chicken order which can be added to the bread order to create a different
order all together called as chicken + bread order. The chicken order is created by inheriting
from the order decorator class.
Any call to this object first invokes custom functionality of order chicken and then invokes
the housed object functionality. For instance you can see When prepare function is called it
first called prepare chicken functionality and then invokes the prepare functionality of the
housed object.
The calculate cost also adds the chicken cost and the invokes the housed order cost to sum up
the total.
Collapse | Copy Code
class OrderChicken : OrderDecorator
{
public OrderChicken(IOrder oOrder) : base(oOrder)
{
}
public override string Prepare()
{

return base.Prepare() + PrepareChicken();


}
private string PrepareChicken()
{
string strPrepare = "";
strPrepare = "\nGrill the chicken\n";
strPrepare = strPrepare + "Stuff in the bread";
return strPrepare;
}
public override double CalculateCost()
{
return base.CalculateCost() + 300.12;

Same way we can also prepare order drinks.


Collapse | Copy Code
class OrderDrinks : OrderDecorator
{
public OrderDrinks(IOrder oOrder)
: base(oOrder)
{
}
public OrderDrinks()
{
}
public override string Prepare()
{
return base.Prepare() + PrepareDrinks();
}
private string PrepareDrinks()
{
string strPrepare = "";
strPrepare = "\nTake the drink from freezer\n";
strPrepare = strPrepare + "Serve in glass";
return strPrepare;
}
public override double CalculateCost()
{
return base.CalculateCost() + 10.12;
}
}

Step 5:- The final step is see the decorator pattern in action. So from the client side you can
write something like this to create a bread order.
Collapse | Copy Code

IOrder Order =new OrderBread();


Console.WriteLine(Order.Prepare());
Order.CalculateCost().ToString();

Below is how the output will be displayed for the above client call.
Collapse | Copy Code
Order 1 :- Simple Bread menu
Bake the bread in oven
Serve the bread
200.3

If you wish to create the order with chicken, drink and bread, the below client code will help
you with the same.
Collapse | Copy Code
Order = new OrderDrinks(new OrderChicken(new OrderBread()));
Order.Prepare();

Order.CalculateCost().ToString();

For the above code below is the output which combines drinks + chicken + bread.
Collapse | Copy Code

Order 2 :- Drinks with chicken and bread


Bake the bread in oven
Serve the bread
Grill the chicken
Stuff in the bread
Take the drink from freezer
Serve in glass
510.54

In other words you can now attach these behaviors to the main object and change the
behavior of the object on runtime.
Below are different order combination we can generate , thus altering the behavior of the
order dynamically.
Collapse | Copy Code

Order 1 :- Simple Bread menu


Bake the bread in oven
Serve the bread
200.3
Order 2 :- Drinks with chicken and bread
Bake the bread in oven
Serve the bread
Grill the chicken
Stuff in the bread
Take the drink from freezer
Serve in glass
510.54
Order 3 :- Chicken with bread
Bake the bread in oven
Serve the bread
Grill the chicken
Stuff in the bread
500.42
Order 4 :- drink with simple bread
Bake the bread in oven
Serve the bread
Take the drink from freezer
Serve in glass
210.42

(A) Can you explain Faade pattern?


Faade pattern sits on the top of group of subsystems and allows them to communicate in a
unified manner.

Figure: - Faade and Subsystem


Figure Order Faade shows a practical implementation of the same. In order to place an
order we need to interact with product, payment and invoice classes. So order becomes a
faade which unites product, payment and invoice classes.

Figure: - Order Facade


Figure faade in action shows how class clsorder unifies / uses clsproduct,clsproduct
and clsInvoice to implement PlaceOrder functionality.

Figure :- Faade in action

Can you explain chain of responsibility ( COR)?


Chain of responsibility is used when we have series of processing which will be handled by a
series of handler logic. Lets understand what that means. There are situations when a request
is handled by series of handlers. So the request is taken up by the first handler, he either can
handle part of it or can not, once done he passes to the next handler down the chain. This goes
on until the proper handler takes it up and completes the processing.

Figure: - Concept of Chain of Responsibility

Lets try to understand this concept by a small sample example. Consider figure Sample
example where we have some logic to be processed. So there are three series of processes
which it will go through. So process 1 does some processing and passes the same to process
2. Process 2 does some kind of processing and passed the same to process 3 to complete the
processing activity.

Figure: - Sample example


Figure class diagram for COR the three process classes which inherit from the same abstract
class. One of the important points to be noted is that every process points to the next process
which will be called. So in the process class we have aggregated one more process object
called as objProcess. Object ObjProcess points to next process which should be called
after this process is complete.

Figure: - Class diagram for COR


Now that we have defined our classes its time to call the classes in the client. So we create all
the process objects for process1 , process2 and process3. Using the setProcess method we
define the link list of process objects. You can see we have set process2 as a link list to
process1 and process2 to process3. Once this link list is established we run the process which
in turn runs the process according to the defined link list.

Figure: - COR client code

Can you explain proxy pattern?


Proxy fundamentally is a class functioning as in interface which points towards the actual
class which has data. This actual data can be a huge image or an object data which very large
and can not be duplicated. So you can create multiple proxies and point towards the huge
memory consuming object and perform operations. This avoids duplication of the object and
thus saving memory. Proxies are references which points towards the actual object.
Figure Proxy and actual object shows how we have created an interface which is
implemented by the actual class. So the interface IImageProxy forms the proxy and the class
with implementation i.e. clsActualImage class forms the actual object. You can see in the
client code how the interface points towards the actual object.

Figure: - Proxy and actual object


The advantages of using proxy are security and avoiding duplicating objects which are of
huge sizes. Rather than shipping the code we can ship the proxy, thus avoiding the need of
installing the actual code at the client side. With only the proxy at the client end we ensure
more security. Second point is when we have huge objects it can be very memory consuming
to move to those large objects in a network or some other domain. So rather than moving
those large objects we just move the proxy which leads to better performance.

Can you explain template pattern?


Template pattern is a behavioral pattern. Template pattern defines a main process template
and this main process template has sub processes and the sequence in which the sub
processes can be called. Later the sub processes of the main process can be altered to
generate a different behavior.
Collapse | Copy Code
Punch :- Template pattern is used in scenarios where we want to create
extendable behaviors in generalization and specialization relationship.

For example below is a simple process to format data and load the same in to oracle. The data
can come from various sources like files, SQL server etc. Irrespective from where the data
comes, the overall general process is to load the data from the source, parse the data and then
dump the same in to oracle.

Figure: - General Process


Now we can alter the general process to create a CSV file load process or SQL server load
process by overriding Load and Parse sub process implementation.

Figure: - Template thought Process


You can see from the above figure how we have altered Load and Parse sub process to
generate CSV file and SQL Server load process. The Dump function and the sequence of
how the sub processes are called are not altered in the child processes.
In order to implement template pattern we need to follow 4 important steps:1. Create the template or the main process by creating a parent abstract class.
2. Create the sub processes by defining abstract methods and functions.

3. Create one method which defines the sequence of how the sub process methods will
be called. This method should be defined as a normal method so that we child
methods cannot override the same.
4. Finally create the child classes who can go and alter the abstract methods or sub
process to define new implementation.
Collapse | Copy Code
public abstract class GeneralParser
{
protected abstract void Load();

protected abstract void Parse();


protected virtual void Dump()
{
Console.WriteLine("Dump data in to oracle");
}
public void Process()
{
Load();
Parse();
Dump();
}

The SqlServerParser inherits from GeneralParser and overrides the Load and Parse
with SQL server implementation.
Collapse | Copy Code
public class SqlServerParser : GeneralParser
{
protected override void Load()
{
Console.WriteLine("Connect to SQL Server");
}
protected override void Parse()
{
Console.WriteLine("Loop through the dataset");
}
}

The FileParser inherits from General parser and overrides the Load and Parse methods
with file specific implementation.
Collapse | Copy Code

public class FileParser : GeneralParser


{
protected override void Load()
{
Console.WriteLine("Load the data from the file");
}
protected override void Parse()
{
Console.WriteLine("Parse the file data");
}

From the client you can now call both the parsers.
Collapse | Copy Code

FileParser ObjFileParser = new FileParser();


ObjFileParser.Process();
Console.WriteLine("-----------------------");
SqlServerParser ObjSqlParser = new SqlServerParser();
ObjSqlParser.Process();
Console.Read();

The outputs of both the parsers are shown below.


Collapse | Copy Code

Load the data from the file


Parse the file data
Dump data in to oracle
----------------------Connect to SQL Server
Loop through the dataset
Dump data in to oracle

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.
To give you a practical understanding i have put all the design patterns and UML in a video
format and uploaded here. You can visit this Web site and download the complete architecture
interview questions PDF which covers SOA , UML , Design patterns , Togaf , OOPs etc.
Download my 500 FAQ Ebook from link below
http://www.questpond.com/SampleDotNetInterviewQuestionBook.zip
In my previous section we had concentrated on design patterns which is one of the most
important fundamentals for architecture interviews. In case you have missed it below are the
link. One of the other areas other than design patterns which needs to be stronger for
architects is putting appropriate UML diagrams in design document.
Some of my previous articles i am sure you will love it.
Design Pattern FAQ - SoftArch4.aspx
Building loosely coupled architecture using IOC and DI: IOCDI.aspx.
Writing flexible business validation http://www.codeproject.com/KB/aspnet/Questpond.aspx
Happy job hunting......
(B) Define UML?

Unified Modeling Language, a standard language for designing and documenting a system in
an object-oriented manner. It has nine diagrams which can be used in design document to
express design of software architecture.
(I) Can you explain use case diagrams?

Use case diagram answers what system does from the user point of view. Use case answer
What will the system do?. Use cases are mainly used in requirement document to depict
clarity regarding a system. There are three important parts in a use case scenario, actor and
use case.
Scenario: A scenario is a sequence of events which happen when a user interacts with the
system.
Actor: Actor is the who of the system, in other words the end user.
Use Case: Use case is task or the goal performed by the end user. Below figure Use Case
shows a simple scenario with Actor and a Use Case. Scenario represents an accountant
entering accounts data in the system. As use cases represent action performed they are
normally represented by strong verbs.
Actors are represented by simple stick man and use case by oval shape as shown in figure
Use Case below.

Figure: Use Case


(I) Can you explain primary and secondary actors?

Actors are further classified in to two types primary and secondary actors. Primary actors are
the users who are the active participants and they initiate the user case, while secondary
actors are those who only passively participate in the use case.
(I) How does a simple use case look like?

Use cases have two views of representation in any requirement document. One is the use
case diagrams and the other is a detail step table about how the use case works. So its like a
pair first an over view is shown using a use case diagram and then a table explaining the same

in detail. Below is a simple login use case shown diagrammatically and then a detail table
with steps about how the use case is executed.

Figure: Login Use Case


Use Case

Rel001

Use Case
Name

Login

Description

This uses depicts the flow of how user will log-in into the chat
application.

Primary
Actor

Simple chat user.

Trigger

User types chat application on URL of the browser.

Precondition

NA

No password is currently present for the system


Assumption Rooms will remain constant as explained in the assumption section of
this document
Failed End
conditions

Duplicate user name is not allowed in the chat application.

Action

User clicks on the log-in button.

Main
Scenario

User types chat application on URL of the browser which in turn


opens the main page.

In the main page of application user is popped up with Enter

user name option and various rooms option drop down menu.

User then types the name and selects one of the room from drop
down menu and then clicks on the Log-in button.

Application then checks whether the user name is unique in the


system if not then user is popped up with error message that
user already exist.

After entering the unique name the user is finally logged in the
application.

Action

NA

Alternate
Scenario

NA

Success
Scenarios

1. Opens page of a selected room in that other user names and their
messages can be seen.

Note and
NA
Open Issues

Table: Login use case table


Note: You must be wondering why we have this pair why not just a use case table only. Use
case diagrams are good to show relationship between use case and they also provide high
over view. The table explanation of a use case talks details about the use case. So when a
developer or a user is reading a requirement document, he can get an overview by looking at
the diagram if he is interested he can read the use case tables for more details.
(I) Can you explain Extend and Include in use cases?

Extend and Include define relationships between use cases. Below figure Extend and
Include shows how these two fundamentals are implemented in a project. The below use
case represents a system which is used to maintain customer. When a customer is added
successfully it should send an email to the admin saying that a new customer is added. Only
admin have rights to modify the customer. First lets define extend and include and then see
how the same fits in this use case scenario.
Include: Include relationship represents an invocation of one use case by the other. If you
think from the coding perspective its like one function been called by the other function.
Extend: This relationship signifies that the extending use case will work exactly like the base
use case only that some new steps will inserted in the extended use case.
Below figure Extend and Include shows that add customer is same as the add discounted
customer. The Add discounted customer has an extra process, to define discount for the

discounted customer which is not available for the simple customer. One of the requirements
of the project was that when we add a customer, the system should send an email. So after the
customer is added either through Add simple customer use case or Add discounted
customer use case it should invoke send a email use case. So we have defined the same
with a simple dotted line with <<include>> as the relationship.

Figure: Extend and Include


Note: One of the points to be noted in the diagram Extend and Include is we have defined
inheritance relationship between simple and admin user. This also helps us defining a
technical road map regarding relationships between simple and admin user.
(I) Can you explain class diagrams?

Class diagram
Class is basically a prototype which helps us create objects. Class defines the static structure
of the project. A class represents family of an object. By using Class we can create uniform
objects.
In the below figure you can see how the class diagram looks. Basically there are three
important sections which are numbered as shown in the below. Lets try to understand
according to the numbering:

Class name: This is the first section or top most section of the Class which
represents the name of the Class (clsCustomer).

Attributes: This is the second section or the middle section of the class
which represents the properties of the system.

Methods: This section carries operation or method to act on the attributes.

Figure: Three sections of the class


Now in the next section we will have a look on Association relationship between these
classes.
(B) How do we represent private, public and protected in class diagrams?

In order to represent visibility for properties and methods in class diagram we need to place
symbols next to each property and method as shown in figure Private, Public and Protected.
+ indicates that its public properties/methods. -indicates private properties which means it
can not be accessed outside the class. # indicate protected/friend properties. Protected
properties can only be seen within the component and not outside the component.

Figure: Private, public and protected


(I) what does associations in a class diagram mean?
Associations in Class diagrams
A single Class cannot represent the whole module in a project so we need one or
more classes to represent a module. For instance, a module named customer
detail cannot be completed by the customer class alone , to complete the whole

module we need customer class, address class, phone class in short there is
relationship between the classes. So by grouping and relating between the
classes we create module and these are termed as Association. In order to
associate them we need to draw the arrowed lines between the classes as shown
in the below figure.

In the figure Order is paid by payments class, we can see Order class and the Payment class
and arrowed line showing relationship that the order class is paid using payment class in
other words order class is going to be used by payment class to pay the order. The left to right
marked arrow basically shows the flow that order class uses the payment class.
In case payment class using the order class then the marked arrow should be right to left
showing the direction of the flow.

Figure:- Order is paid by Payments class


There are four signs showing the flow:-

Figure: Direction signs in UML


Multiplicity

Multiplicity can be termed as classes having multiple associations or one class can be linked
to instances of many other classes. If you look at the below figure the customer class is
basically associated with the address class and also observes the notations (*, 0 and 1).If you
look at the right hand side the (1.*) notation indicates that at least one or many instance of
the address class can be present in the customer class. Now towards left hand side we have
(0.*) notation indicating that address class can exist without or many customer class can
link him.
In order to represent multiplicity of classes we have to show notations like (1.*), (0.*) as
shown in below figure.

Note: * means many where as (0, 1) means (zero or at least one) respectively.

Figure: Multiplicity in Classes


(I) Can you explain aggregation and composition in class diagrams?

In this Association there are two types mainly Aggregation Association and Composition
Association.
Aggregation Association signifies that the whole object can exist without the Aggregated
Object. For example in the below figure we have three classes university class, department
class and the Professor Class. The university cannot exist without department which means
that university will be closed as the department is closed. In other words lifetime of the
university depend on the lifetime of department.
In the same figure we have defined second Association between the department and the
Professor. In this case, if the professor leaves the department still the department continues in
other words department is not dependent on the professor this is called as Composition
Association.
Note: The filled diamond represents the aggregation and the empty diamond represents the
composition. You can see the figure below for more details.

Figure: Aggregation and composition in action


(A) What are composite structure diagram and reflexive association in class
diagrams?
Composite structure diagram

When we try to show Aggregation and Composition in a complete project the diagram
becomes very complicated so in order to keep it simple we can use Composite structure
diagram. In the below figure we have shown two diagrams one is normal diagram other is
Composite structure diagram and the simplicity can easily be identified. In the composite
diagram the aggregated classes are self contained in the main class which makes it simpler to
read.

Figure: Composite Structure diagram


Reflexive associations

In many scenarios you need to show that two instances of the same class are associated with
each other and this scenario is termed as Reflexive Association. For instance in the below
figure shows Reflexive Association in the real project. Here you can see customer class has
multiple address class and addresses can be a Head office, corporate office or Regional office.
One of the address objects is Head office and we have linked the address object to show
Reflexive Association relationship. This is the way we can read the diagram Regional address
object is blocked by zero or one instance of Head office object.

Figure: Reflexive association


(I) Can you explain business entity and service class?

Business entity objects represent persistent information like tables of a database. Just making
my point clearer they just represent data and do not have business validations as such. For
instance below figure Business entity and service shows a simple customer table which with
three fields Customer Code, Customer Address and Phone Number. All these fields are
properties in ClsCustomer class. So ClsCustomer class becomes the business entity class.

The business entity class by itself can not do anything its just a place holder for data. In the
same figure we have one more class ClsServiceCustomer. This class aggregates the
business entity class and performs operations like Add, Next (Move to next record), Prev
(Move to previous record) and GetItem (get a customer entity depending on condition).
With this approach we have separated the data from the behavior. The service represents the
behavior while the business entity represents the persistent data.

Figure:-Business entity and service


(I) Can you explain System entity and service class?

System entity class represents persistent information which is related to the system. For
instance in the below figure System entity and service class we have a system entity class
which represents information about loggedindate and loggedintime of the system registry.
System service class come in two flavors one is it acts like a wrapper in the system entity
class to represent behavior for the persistent system entity data. In the figure you can see how
the ClsAudit system entity is wrapped by the ClsAuditSytem class which is the system
service class. ClsAuditSystem adds Audit and GetAudit behavior to the ClsAudit
system entity class.

Figure: System entity and service class


The other flavor of the system service class is to operate on non-persistent information. The
first flavor operated on persistent information. For instance the below figure Non-persistent
information shows how the class ClsPaymentService class operates on the payment
gateway to Check is the card exists , Is the card valid and how much is the amount in the card
?. All these information are non-persistent. By separating the logic of non-persistent data in to
a system service class we bring high reusability in the project.

Figure: Non-persistent information


Note: The above question can be asked in interview from the perspective of how you have
separated the behavior from the data. The question will normally come twisted like How did
you separate the behavior from the data?.
(B) Can you explain generalization and specialization?
Generalization and Specialization

In Generalization and Specialization we define the parent-child relationship between the


classes. In many instance you will see some of the classes have same properties and operation
these classes are called super class and later you can inherit from super class and make sub
classes which have their own custom properties. In the below figure there are three classes to
show Generalization and Specialization relationship. All phone types have phone number as a
generalized property but depending upon landline or mobile you can have wired or simcard

connectivity as specialized property. In this diagram the clsphone represent Generalization


whereas clslandline and clsmobile represents specialization.

Figure: Generalization and Specialization


(B) How do we represent an abstract class and interface UML?

Interface is represented by <<type>> in the class diagram. Below figure Interface in action
shows we have defined an interface IContext. Note the <<type>> represents an interface.
If we want to show that the interface is used in a class we show the same with a line and a
simple circle as shown in figure Interface in Action below.

Figure: Interface in action


Abstract classes are represented by {abstract} as shown in figure Abstract classes in
action.

Figure: Abstract classes in action.


(B) How do we achieve generalization and specialization?

By using inheritance.
(I) Can you explain object diagrams in UML?

Class represents shows the static nature of the system. From the previous question you can
easily judge that class diagrams shows the types and how they are linked. Classes come to
live only when objects are created from them. Object diagram gives a pictorial representation
of class diagram at any point of time. Below figure Object diagram shows how a class looks
in when actual objects are created. We have shown a simple student and course relationship in
the object diagram. So a student can take multiple courses. The class diagram shows the same
with the multiplicity relationship. We have also shown how the class diagram then looks
when the objects are created using the object diagram. We represent object with Object
Name: Class Name. For instance in the below figure we have shown Shiv : ClsStudent i.e
Shiv is the object and ClsStudent the class. As the objects are created we also need to
show data of the properties, the same is represented by PropertyName=Value i.e.
StudentName=Shiv.

Figure: Object diagrams


The diagram also states that ClsStudent can apply for many courses. The same is
represented in object diagram by showing two objects one of the Computer and the other of
English.
Note: Object diagrams should only be drawn to represent complicated relationship between
objects. Its possible that it can also complicate your technical document as lot. So use it
sparingly.
(I) Can you explain sequence diagrams?
Sequence diagrams

Sequence diagram shows interaction between objects over a specific period time. Below
figure 'Sequence diagram' shows how a sequence diagram looks like. In this sequence
diagram we have four objects 'Customer','Product','Stock' and 'Payment'. The message flow is
shown vertically in waterfall manner i.e. it starts from the top and flows to the bottom.
Dashed lines represent the duration for which the object will be live. Horizontal rectangles on
the dashed lines represent activation of the object. Messages sent from a object is represented
by dark arrow and dark arrow head. Return message are represented by dotted arrow. So the
figure shows the following sequence of interaction between the four objects:

Customer object sends message to the product object to request if the


product is available or not.

Product object sends message to the stock object to see if the product
exists in the stock.

Stock object answers saying yes or No.

Product object sends the message to the customer object.

Customer object then sends a message to the payment object to pay


money.

Payment object then answers with a receipt to the customer object.

One of the points to be noted is product and stock object is not active when the payment
activity occurs.

Figure: Sequence diagram


Messages in sequence diagrams

There are five different kinds of messages which can be represented by sequence.
Synchronous and asynchronous messages

Synchronous messages are represented by a dark arrow head while asynchronous messages
are shown by a thin arrow head as shown in figure Synchronous and Asynchronous.

Figure: Synchronous and Asynchronous

Recursive message

We have scenarios where we need to represent function and subroutines which are called
recursively. Recursive means the method calling himself. Recursive messages are represented
by small rectangle inside a big rectangle with an arrow going from the big rectangle to the
small rectangle as shown in figure Recursive message.

Figure: Recursive message


Message iteration

Message iteration represents loops during sequences of activity. Below figure message
iteration shows how order calls the orderitem objects in a loop to get cost. To represent
loop we need to write For each <<object name>>. In the below figure the object is the
orderitem. Also note the for each is put in a box to emphasize that its a loop.

Figure: Message iteration


Message constraint

If we want to represent constraints it is put in a rectangle bracket as shown in figure message


constraint. In the below figure message constraint the customer object can call book
tickets only if the age of the customer is greater than 10.

Figure: Message constraint


Message branching

Below figure message branching shows how customer object have two branches one is
when the customer calls save data and one when he cancels the data.

Figure: Message branching


Doing Sequence diagram practically

Lets take a small example to understand sequence diagram practically. Below is a simple
voucher entry screen for accounts data entry. Following are the steps how the accountant will
do data entry for the voucher:

Accountant loads the voucher data entry screen. Voucher screen loads
with debit account codes and credit account codes in the respective
combo boxes.

Accountant will then fill in all details of the voucher like voucher
description, date, debit account code, credit account code, description,
and amount and then click add voucher button.

Once add voucher is clicked it will appear in the voucher screen below in
a grid and the voucher entry screen will be cleared and waiting for new
voucher to be added. During this step voucher is not added to database
its only in the collection.

If there are more vouchers to be added the user again fills voucher and
clicks add voucher.

Once all the vouchers are added he clicks submit voucher which finally
adds the group of vouchers to the database.

Below figure Voucher data entry screen shows pictorially how the screen looks like.

Figure: Voucher data entry screen


Figure Voucher data entry sequence diagram shows how the sequence diagram looks like.
Below diagram shows a full sequence diagram view of how the flow of the above screen will
flow from the user interface to the data access layer. There are three main steps in the
sequence diagram, lets understand the same step by step.
Step 1:- The accountant loads the voucher data entry screen. You can see from the voucher
data entry screen image we have two combo boxes debit and credit account codes which are
loaded by the UI. So the UI calls the Account Master to load the account code which in turn
calls the data access layer to load the accounting codes.
Step 2:- In this step the accountant starts filling the voucher information. The important point
to be noted in this step is that after a voucher is added there is a conditional statement which
says do we want to add a new voucher. If the accountant wants to add new voucher he again
repeats step 2 sequence in the sequence diagram. One point to be noted is the vouchers are
not added to database they are added in to the voucher collection.

Step 3:- If there are no more vouchers the accountant clicks submit and finally adds the entire
voucher in the database. We have used the loop of the sequence diagram to show how the
whole voucher collection is added to the database.

Figure: Voucher data entry sequence diagram


Other Interview question PDF's

Project Management interview questions

Download Java Interview Questions

Download Software Architecture Interview Questions

http://www.codeproject.com/KB/aspnet/SoftArch7.aspx
(I) Can you explain collaboration diagrams ?

Collaboration diagrams
Collaboration diagrams provide the same information as shown by sequence diagram but they
show it in a different way. In sequence diagram we pay more attention to the time and
sequence order, but in collaboration diagram we pay more emphasis on the interaction
messages between the objects.

Figure Collaboration diagrams shows how a collaboration diagram looks like. Below are
some points you can easily pick up looking at the figure: Objects are represented in rectangle.
Messages are represented by an arrow and sequence number. For instance in figure
collaboration diagrams we can see the order product has a arrow which shows that the
message is sent from the customer object to the product and 1 represents that its the first
messages.
Conditional statements are denoted by square brackets [.
We can also group sequence numbers by grouping them using decimals. For instance Pay
by master and Pay by Visa are all grouped in to message sequence number 3 (Do
payment). So they are denoted by 3,3.1 and 3.2 respectively.

Figure: - Collaboration diagrams


You can represent the for each loop using the for each keyword as shown in below figure
for each in collaboration.

Figure: - For each in collaboration


Note: - Try drawing a collaboration diagram for the same voucher data entry screen.
Sequence and collaboration diagrams are also called as iteraction diagrams.
(I) Can you explain activity diagrams?

Activity diagrams
Activity diagram are used to capture complicated process flows in a system. Below figure
Activity shows a simple activity diagram. Some of the points which you can easily note
from the activity diagram figure are: Start of an activity is denoted by a dark circle.
End of an activity is denoted by a dark circle inside a white circle.
Activities are denoted by simple oval rectangles.

Figure: - Activity

A decision in activity diagram is as shown figure Decision in Activity Diagram. Figure


shows the condition in a [ (Square bracket). So the first activity is Check Age, if the age is
greater than 16 then we can go for Adult Movie activity or else we need to execute the
Kids Movie activity.

Figure: - Decision in Activity Diagram

There are situations in project where we need to execute two parallel activities in a project. A
solid bold line represents from where the activities will split and execute in parallel and then
again a solid line is where the parallel activities will meet. For instance in the below figure
Parallel Processing we can see how Make lemon juice and Make Ginger Juice activities
are executed in parallel.

Figure: - Parallel Processing


In big and complex activity diagrams its very difficult to figure out which object is
responsible for which activities. This problem is solved by Swimlanes. Consider the below
figure Without Swimlanes. The whole activity diagram looks very complex and its very
difficult to figure out which object is responsible for which activity.

Figure: - Without Swimlanes

Now see the below figure With Swimlanes we have partitioned the activity to the respective
objects like Customer, Stock, Order processing, Payment and Invoice. These partitions are
termed as Swimlanes , so if you feel that the activity diagram is complex think about using
Swimlanes it can really make your activity diagram readable.

Figure: - With Swimlanes


(I) What is state chart diagram?

State Chart Diagram


State diagram depicts different states that an object goes through during their life cycle. State
diagram depicts how an object responds to events. We think state diagrams as optional and
should be used if your project has scenarios where the object goes through lot of complicated
states and transitions. If your project does not have such kind of scenarios then sequence,
collaboration or activity would be sufficient to meet your needs. So all objects have states and
an object moves from one state to other state when there is some event or transition.
There are three important things when we consider state of an object event, guard and action.
Lets first define these three things: - .
Action: - Action triggers an object state from one state to another.
Event: - Event triggers the action.
Guard: - Guard is condition on which it evaluates which action to be triggered.

These three things are principle component of state chart diagrams. Below figure Types of
event and action shows how they are represented in state chart diagrams.

Figure: - Types of Event and Action


There are three ways by which we can represent the same.
Type 1:- This methodology of writing is used when we need to map an event with action
using a guard. For instance in the above figure Types of Event and Action shows the event
mouse click, guard double click and the resulting action open folder.
Type 2:- The guard is optional. For instance sometimes we only have events and actions, i.e.
with out the guard. For instance when the even On happens the action is that Light Bulb is
on.
Type 3:- This type of representation shows an infinite loop for an action. For instance the
Watch will be running infinitely during a state, as shown in figure Type of Event and
Action.
Now that we know how to write event, actions and guard, lets see how state diagram looks
like. Below figure State example shows how a state looks like. Its an oval rectangle as
shown below. In order to show a transition we need to show an arrow from one state to other
state as shown in figure State example.

Figure: - State example

Below figure Sample state chart shows a simple state chart diagram. Some points which are
immediately visible from the diagrams are as follows: A dark black arrow indicates start of a state chart diagram.
A dark circle with a white circle outside indicates end of a state chart diagram.
Circular rectangle indicates state while arrows indicate events / transitions.

Figure: - Sample state chart

State is represented as shown in figure Basic element of state diagram. Its a simple
rectangle which is rounded. In the top section we give the state name. The below section is

optional which has do/action. It represents a long running activity when the object goes
through this state.
(I) Can you explain stereotypes in UML?

Stereotypes are a way to define variations on existing UML model. This variation is brought
in to place to extend UML in a consistent manner. They are displayed in double less than and
double greater than sign with a simple text as shown below. The below figure shows at the
left hand side a class diagram with out stereo types while the right hand side shows with
stereo types. You can easily make out how the class diagram is readable with stereo types.
For instance the Customer() can be mistaken for a method but we have clarified that its a
constructor by using stereo types.

Figure: - Stereotypes

Below are some of the commonly used stereo types while writing UML.
<<Application>>:- Used to represent a UI system in a application.
<<Database>> :- represents a database in a application.
<<Table>> :- A table with in database.
<<Library>> :- A reusable library or function.
<<File>> :- Physical file on a folder.
<<Executable>> :- A software component which can be executed.
<<Web services>> :- Represents a web service.
<<JDBC>> :- Java database connectivity , a JAVA API to connect to database.
<<ODBC>> :- Open database connectivity , a Microsoft API to connect to database.

(I) Can you explain package diagrams?

Packages are like folders in a system which allows you to logically group UML diagrams.

They make complex UML diagram readable. In actual projects they are used to logically
group use cases and classes. So we can say there are two types of package diagrams one is
class package diagram and other is use case package diagram. Package diagram depict a high
level of overview for class and use cases.
Class package diagram: - Class package diagram are used to logical group classes. You can
think that package technically map to Package in JAVA and Namespaces in C# and
VB.NET. Packages are denoted by small rectangle on a big rectangle as shown in figure
Package diagram. One of the points to be noted is the stereotypes. We have numbered the
figure so that we can understand it better.
1 We are using the MVC (Model View controller) framework. So we have denoted this
package using the << Framework >> stereo type. Refer the commonly used stereo type table
discussed in the previous sections.
2 and 3 Book tickets is the second package which inherits from the MVC model. The
stereo type is <<application>> which means its a user interface.
4 A simple line shows a link between two classes stating that one class package uses the
other class package.
5 This package is collection of the booking engine library.
6 The final package is the database.

Figure: - Package diagram

As said before packages are nothing but collection of logical classes or any UML entity. We

have shown the detail of the above package diagram. We should restrict from using package
diagram for showing the in depth architecture as it can become very complicated. For
instance the below diagram Detail Package diagram shows how complicated it can look if
use the package diagram to show in depth architecture. To avoid complication its good to
only draw an over all diagram as shown in Package diagram.

Figure: - Detail Package diagram

Use case package diagram: - The way we have logically grouped classes we can also use the
package diagram to logically group use cases. Below figure shows how a use case package
diagram looks like.

Figure: - Use Case Package

(B) Can you explain component diagrams?

Component diagrams achieve the same objective like package diagrams. They show the
dependencies among software components. Below figure Component diagram shows a
sample component diagram for simple data entry application which uses a web service to
interact with the database. We have numbered the steps to understand the details of the
component diagram.
1 Two rectangles are shown to represent a component of a system.
2 Stereo types are used to denote what kind of system it represents.
3 A line with a circle denotes an interface by which the external world can interact with the
component. For instance in the figure we have represented a Customer Web service which
can is interacted by using XML.

Figure: - Component Diagram


(B) Can you explain deployment diagrams?

Deployment diagrams represents an overall static view of how software and hardware nodes
in the application. They show what the hardware is and which components are installed on
which hardware. In deployment diagram we represent the hardware with a solid box and
simple underlined text description showing which hardware is it. You can have more than one
component on a single hardware. So the browser is an application UI which resides on the
workstation computer and the database and web server resides on the web server hardware.
Deployment diagram can be more complex with firewalls, payment gateways, PDA devices,
VPN etc.

Figure: - Deployment diagram


(I) Can you explain how UML flows in actual project?

In actual projects we do not draw all the diagrams. Every UML diagram is made for a
purpose. It completely depends on whats the nature of the project. In short you should ask
yourself questions like, is this diagram important, whats my need etc. So below is a flow
which you can follow in your project, again as we said it depends on what kind of scenario
you want to depict.

Figure: - UML flow in actual projects


The first step is to derive use cases from the requirement documents.
Once use cases are derived we need to decide the messages which will flow in the system.
This can be done using interaction diagrams. If you need to know the object creation life
times we use the sequence diagram and if we want to concentrate on the messages we use the
collaboration diagrams. So depending on scenario we need to make a choice which diagram
we need to draw.
Now that we are clear about messages we can draw class diagrams to depict the static part
of the project i.e. classes.
If we find any complicated class relationships we draw object diagrams.
If we need to depict any complicated code we need to represent same with a activity
diagram.
Finally to give an overview of the project we can use package diagram, component or

deployment diagram. As said before we can use combination of component and deployment
diagram to give a overview of the architecture.
(B) What is SOA?

SOA stands for service oriented architecture. Before we define SOA lets first define a service.
In real world service is what we pay for and we get the intended service. For instance you go
to a hotel and order food. Your order first goes to the counter and then it goes to the kitchen
where the food is prepared and finally the waiter serves the food.

Figure: - Hotel and services

So in order to order a item from a hotel you need the three logical departments / services to
work together (counter, kitchen and waiter).
In the same manner in software world these services are termed as business services. They
are self contained and logical. So lets first define a business service, SOA definition will be
just an extension of the same.
Definition of business service: - Its a logical encapsulation of self contained business
functionality.
For instance figure order system shows a simple ordering system which is achieved by
different services like payment gateway, stock system and delivery system coming together.
All the services are self contained and logical. They are like black boxes. In short we do not
need to understand the internal details of how the business service works. For the external
world its just a black box which takes messages and serves accordingly. For instance the
payment gateway business service takes message check credit and gives out output does
the customer have credit or not. For the order system business service payment gateway
service is a black box.

Figure: - Order system

Now lets revise some bullet points of SOA before we arrive to a definition of SOA.
SOA components are loosely coupled. When we say loosely coupled means every service
is self contained and exist in alone logically. For instance we take the payment gateway
service and attach it to a different system.
SOA services are black boxes. In SOA services hide there inner complexities. They only
interact using messages and send services depending on those messages. By visualizing
services as black boxes services become more loosely coupled.
SOA service should be self defined: - SOA services should be able to define themselves.
SOA Services are maintained in a listing: - SOA services are maintained in a central
repository. Applications can search the services in the central repository and use them
accordingly.
SOA components can be orchestrated and linked to achieve a particular functionality.
SOA services can be used/orchestrated in a plug and play manner. For instance figure
Orchestration shows two services Security service and Order processing service. You can
achieve two types of orchestrations from it one you can check the user first and then process
order or vice-versa. Yes you guessed right using SOA we can manage work flow between
services in a loosely coupled fashion.

Figure: - Orchestration
So lets define SOA.
SOA is a architecture for building business applications using loosely coupled services which
act like black boxes and can be orchestrated to achieve a specific functionality by linking
together.
(I) In SOA do we need to build systems from scratch?

No. If you need to integrate or make an existing system as a business service, you just need to
create loosely coupled wrappers which will wrap your custom systems and expose the
systems functionality in generic fashion to the external world.
(I) Can you explain business layers and plumbing layers in SOA?

In SOA we can divide any architecture in two layers. The first which has direct relevance to
business as it carries out business functions. The second layer is a technical layer which talks
about managing computer resources like database, web server etc. This division is needed to
identify a service. Consider the figure Simple order system. It has various components
which interact with each other to complete the order system functionality.

Figure: - Simple order System


The simple order system can be divided in to two layers (see figure business and plumbing
layer one which is business related and second which is more technical related. You can see
the plumbing layer consisting of data access layer , AJAX , yes more of technical stuff.

Figure: - Business layer and plumbing layer


(I) whats the difference between services and components?

Services are logical grouping of components to achieve business functionality. Components


are implementation approaches to make a service. The components can be in JAVA, C#, C++
but the services will be exposed in a general format like Web Services.
(A) Can you describe the complete architecture of SOA?

Figure Architecture of SOA shows a complete view of a SOA. Please note this architecture
diagram is not tied up with implementation of Microsoft, IBM etc. Its a general architecture.
Any vendor who implements SOA needs to fulfill the below SOA components. How they do
it is completely their own technological implementation.

Figure: - Architecture of SOA

The main goal of SOA is to connect disparate systems. In order that these disparate system
work they should messages to each other. ESB (Enterprise service bus) acts like a reliable
post office which guarantees delivery of messages between systems in a loosely coupled
manner. ESB is a special layer which delivers messages between applications. In the figure
we have shown a huge plump pipe. Its not hardware or some wire etc. Its a group of
components/software which helps you to send and receive messages between the disparate
applications. Do not try to code your own ESB, you can think of buying one from Microsoft,
IBM, Oracle, progress etc.
SOA registry is like a reference database of services. It describes what each services do,
where are they located and how can they communicate. Its a central reference of meta-data
for services.
SOA workflow allows us to define work flow using the services in SOA registry. We will
read more about BPM in the further questions.

Service broker reads the work flow and takes services from the SOA registry and ties them
together. Service brokers are normally middleware like EAI (Enterprise application
Integration) products. You can get a list of decent EAI from Sun, Microsoft, and IBM etc.
Process manager is nothing but the collection of SOA registry, SOA workflow and service
broker.
SOA supervisor is traffic cop ensuring that services do not have issues. It deals mainly with
performance issues of the system so that appropriate service levels are met. If any of the
services have performance problems it sends messages to the proper infrastructure to fix the
issue.
Note: - The above explanation is of general architecture for SOA. Any vendor (Microsoft,
IBM, SUN etc) who gives solution for SOA should have the above components in some or
other manner. As this is a Software architecture book, we will not be covering specific
vendor implementation. We would advise the reader to map the same to their vendor
products for better understanding.

(I) Can you explain a practical example in SOA?

(I) What are ends, contract, address, and bindings?

These three terminologies on which SOA service stands. Every service must expose one or
more ends by which the service can be available to the client. End consists of three important
things where, what and how: Contract (What)

Contract is an agreement between two or more parties. It defines the protocol how client
should communicate with your service. Technically, it describes parameters and return values
for a method.
Address (Where)
An Address indicates where we can find this service. Address is a URL, which points to the
location of the service.
Binding (How)
Bindings determine how this end can be accessed. It determines how communications is
done. For instance, you expose your service, which can be accessed using SOAP over HTTP
or BINARY over TCP. So for each of these communications medium two bindings will be
created.
Below figure, show the three main components of end. You can see the stock ticker is the
service class, which has an end hosted on www.soa.com with HTTP and TCP binding support
and using Stock Ticker interface type.

Figure: - Endpoint Architecture

Note: - You can also remember the end point by ABC where A stands for Address, B for
bindings and C for Contract.

(I) Are web-services SOA ?

SOA is a thinking, its an architectural concept and web service is one of the technical
approach to complete it. Web services are the preferred standards to achieve SOA.
In SOA we need the services to be loosely coupled. A web service communicates using

SOAP protocol which is XML based which is very loosely coupled. It answers the what part
of the service.
SOA services should be able to describe themselves.WSDL describes how we can access
the service.
SOA services are located in a directory.UDDI describes where we can get the web service.
This nothing but implementation of SOA registry.

You might also like