Design Patterns
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.
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.
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.
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.
created, report type is set, headers and footers of the report are set and finally we get the
report for display.
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.
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.
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.
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.
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;
}
}
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.
Step 4: - You can now consume the singleton object using the below code from the client.
Collapse | Copy Code
Below goes the complete code for singleton pattern which we discussed above in pieces.
Collapse | Copy Code
action. The bad thing about the code is it has lot of IF condition which makes the coding
more cryptic.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
Below figure Strategy client code shows how the wrapper class is used and the strategy
object is set on runtime using the setStatergy method.
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.
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.
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.
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.
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.
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.
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 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 :- 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.
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.
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
{
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
Force this interface across all the root objects and leaf / node objects as shown below.
Collapse | Copy Code
}
public bool isValid()
{
return true;
}
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.
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
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
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.
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()
{
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
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
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
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.
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.
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();
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
From the client you can now call both the parsers.
Collapse | Copy Code
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.
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.
Rel001
Use Case
Name
Login
Description
This uses depicts the flow of how user will log-in into the chat
application.
Primary
Actor
Trigger
Precondition
NA
Action
Main
Scenario
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.
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
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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:
Product object sends message to the stock object to see if the product
exists in the stock.
One of the points to be noted is product and stock object is not active when the payment
activity occurs.
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.
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.
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.
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.
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.
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.
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.
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
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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 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.
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.
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.
Note: - You can also remember the end point by ABC where A stands for Address, B for
bindings and C for Contract.
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.