Wednesday, September 9, 2009

UML Interview Questions - Part 1

Introduction

This article is the Part 1 of the UML. Please feel free to download my free 500 question and answer ebook
which covers .NET, ASP.NET, SQL Server, WCF, WPF, WWF @
http://www.questpond.com/

You can visit and download the complete architecture Interview questions PDF
which covers SOA, UML, Design patterns, Togaf, OOPs etc

Happy job hunting......

UML Interview Questions Part 1


(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 case’s represent action performed they are normally represented by strong verbs.
Actor’s 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 case’s 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 it’s 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



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 diagramClass 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. Let’s 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 it’s 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 diagramsA 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 it’s 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 <>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. It’s 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 it’s 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

Let’s 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 it’s 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, let’s 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

Tuesday, September 8, 2009

Design Pattern Interview Questions - Part 4

Introduction

This article is the Part 4 of the Design Pattern. Please feel free to download my free 500 question and answer ebook which covers .NET, ASP.NET, SQL Server, WCF, WPF, WWF @ http://www.questpond.com/
You can visit and download the complete architecture Interview questions PDF which covers SOA, UML, Design patterns, Togaf, OOPs etc

Happy job hunting......
You can download the software architecture interview questions PDF Download Software Architecture Interview Questions

Design Pattern Interview Questions - Part 4


(A) 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
Let’s 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


(A) Can you explain composite pattern?

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 let’s 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.
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”.
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.
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.
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.
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.
public class Phone : IBusinessObject
    {
        public void Update()
        {}
        public bool isValid()
        {return true;}
        public void Add(object o)
        {
            // no implementaton
        }
    }

(I) Can you explain decorator pattern?

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.
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.
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.
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.
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.
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.
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.
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.
IOrder Order =new OrderBread();
Console.WriteLine(Order.Prepare());
Order.CalculateCost().ToString();
Below is how the output will be displayed for the above client call.
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.
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.
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.
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 Façade pattern?

Façade pattern sits on the top of group of subsystems and allows them to communicate in a unified manner
Figure: - Façade and Subsystem
Figure ‘Order Façade’ 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 façade which unites product, payment and invoice classes.

Figure: - Order Facade
Figure ‘façade in action’ shows how class ‘clsorder’ unifies / uses ‘clsproduct’,’clsproduct’ and ‘clsInvoice’ to implement ‘PlaceOrder’ functionality.


Figure :- Façade in action

Note:- You can find the façade code in the ‘façade pattern’ folder.


(A) 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. Let’s 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

Let’s 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
Note :- You can get the code for the same in C# in ‘ChainOfResponsibility’ folder.


(I) 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.
Note :- You can get the proxy code in the ‘Proxy Pattern’ folder.


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

Other Interview question PDF's

.NET Interview Question PDF

Monday, September 7, 2009

Design Pattern Interview Questions - Part 3

Introduction

This article is the Part 3 of the Design Pattern. Please feel free to download my free 500 question and answer ebook which covers .NET, ASP.NET, SQL Server, WCF, WPF, WWF @ http://www.questpond.com/
You can visit and download the complete architecture Interview questions PDF which covers SOA, UML, Design patterns, Togaf, OOPs etc. here
Happy job hunting......

Design Pattern Interview Questions - Part 3

(I) Can you explain state pattern?

State pattern allows an object to change its behavior depending on the current values of the object. Consider the figure ‘State pattern example’. It’s an example of a bulb operation. If the state of the bulb is off and you press the switch the bulb will turn off. If the state of bulb is on and you press the switch the bulb will be off. So in short depending on the state the behavior changes.
Figure: - State pattern example

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

When we click the press switch it toggles to the opposite state of what we have currently.

Figure: - State pattern in action

(I) Can you explain strategy pattern?

Strategy pattern are algorithms inside a class which can be interchanged depending on the class used. This pattern is useful when you want to decide on runtime which algorithm to be used.

Let’s try to see an example of how strategy pattern works practically. Let’s take an example of a math’s calculation where we have strategies like add and substract. Figure ‘Strategy in action’ shows the same in a pictorial format. It takes two numbers and the depending on the strategy it gives out results. So if it’s an addition strategy it will add the numbers, if it’s a substraction strategy it will give the substracted results. These strategies are nothing but algorithms. Strategy pattern are nothing but encapsulation of algorithms inside classes.

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

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

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

(A) Can you explain visitor pattern?

Visitor pattern allows us to change the class structure with out changing the actual class. Its way of separating the logic and algorithm from the current data structure. Due to this you can add new logic to the current data structure with out altering the structure. Second you can alter the structure with out touching the logic.

Consider the below figure ‘Logic and data structure’ where we have a customer data structure. Every customer object has multiple address objects and every address object had multiple phone objects. This data structure needs to be displayed in two different formats one is simple string and second XML. So we have written two classes one is the string logic class and other is the XML logic class. These two classes traverse through the object structure and give the respective outputs. In short the visitor contains the logic.

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

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

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

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

Figure: - Visitor client code
Note: - You can find a sample of the same in C# in the visitor folder of the CD. If you belong to some other programming domain you can map the same as the code is very generic.


(A) What the difference between visitor and strategy pattern?

Visitor and strategy look very much similar as they deal with encapsulating complex logic from data. We can say visitor is more general form of strategy.
In strategy we have one context or a single logical data on which multiple algorithms operate. In the previous questions we have explained the fundamentals of strategy and visitor. So let’s understand the same by using examples which we have understood previously. In strategy we have a single context and multiple algorithms work on it. Figure ‘Strategy’ shows how we have a one data context and multiple algorithm work on it.

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

Figure: - Visitor
So in short strategy is a special kind of visitor. In strategy we have one data context and multiple algorithms while in visitor for every data context we have one algorithm associated. The basic criteria of choosing whether to implement strategy or visitor depends on the relationship between context and algorithm. If there is one context and multiple algorithms then we go for strategy. If we have multiple contexts and multiple algorithms then we implement visitor algorithm.

(A) Can you explain adapter pattern?

Many times two classes are incompatible because of incompatible interfaces. Adapter helps us to wrap a class around the existing class and make the classes compatible with each other. Consider the below figure ‘Incompatible interfaces’ both of them are collections to hold string values. Both of them have a method which helps us to add string in to the collection. One of the methods is named as ‘Add’ and the other as ‘Push’. One of them uses the collection object and the other the stack. We want to make the stack object compatible with the collection object.

Figure: - Incompatible interfaces
There are two way of implementing adapter pattern one is by using aggregation (this is termed as the object adapter pattern) and the other inheritance (this is termed as the class adapter pattern). First let’s try to cover object adapter pattern.

Figure ‘Object Adapter pattern’ shows a broader view of how we can achieve the same. We have a introduced a new wrapper class ‘clsCollectionAdapter’ which wraps on the top of the ‘clsStack’ class and aggregates the ‘push’ method inside a new ‘Add’ method, thus making both the classes compatible.

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

Figure :- Class adapter pattern
Note :- You can the above C# example in the adapter folder of the CD.


(I) What is fly weight pattern?

Fly weight pattern is useful where we need to create many objects and all these objects share some kind of common data. Consider figure ‘Objects and common data’. We need to print visiting card for all employees in the organization. So we have two parts of data one is the variable data i.e. the employee name and the other is static data i.e. address. We can minimize memory by just keeping one copy of the static data and referencing the same data in all objects of variable data. So we create different copies of variable data, but reference the same copy of static data. With this we can optimally use the memory.

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

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

Figure: - Fly weight client code


Other Interview question PDF's