Tuesday, March 18, 2008

Design Patterns Interview QA

What are Design Patterns and why one needs them?


A pattern based designing approach is best suited in devising solutions for problems occurring over and over again.The design patterns are language-independent strategies for solving common object-oriented design problems.

When you design, you should have advanced knowledge of such solutions in order to overcome problems that may occur in your system. GoF, Gang-Of-Four,because of the four authors who wrote, Design Patterns: Elements of Reusable Object-Oriented Software(ISBN 0-201-63361-2) is a software engineering book describing recurring solutions to common problems in software design. The book's authors are Erich Gamma, Richard Helm, Ralph Johnson, and John Vlissides. It is language independent approach of designing systems on the based of patterns.

What are different types of design patterns?


There are three kinds of design patterns:

Creational patterns:

They are related with how objects and classes are created. While class-creation patterns use inheritance effectively in the instantiation process,while object-creation patterns use delegation to get the job done.

* Abstract Factory groups object factories that have a common theme.
* Builder constructs complex objects by separating construction and representation.
* Factory Method creates objects without specifying the exact object to create.
* Prototype creates objects by cloning an existing object.
* Singleton restricts object creation for a class to only one instance.

Structural patterns:

They are related to class and object composition.This pattern uses inheritance to define new interfaces in order to compose new objects and hence new functionalities.

* Adapter allows classes with incompatible interfaces to work together by wrapping its own interface around that of an already existing class.
* Bridge decouples an abstraction from its implementation so that the two can vary independently.
* Composite composes one-or-more similar objects so that they can be manipulated as one object.
* Decorator dynamically adds/overrides behavior in an existing method of an object.
* Facade provides a simplified interface to a large body of code.
* Flyweight reduces the cost of creating and manipulating a large number of similar objects.
* Proxy provides a placeholder for another object to control access, reduce cost, and reduce complexity.

Behavioral patterns:

These design patterns deal with objects communication. They are specifically concerned with communication between objects.

* Chain of responsibility delegates commands to a chain of processing objects.
* Command creates objects which encapsulate actions and parameters.
* Interpreter implements a specialized language.
* Iterator accesses the elements of an object sequentially without exposing its underlying representation.
* Mediator allows loose coupling between classes by being the only class that has detailed knowledge of their methods.
* Memento provides the ability to restore an object to its previous state (undo).
* Observer is a publish/subscribe pattern which allows a number of observer objects to see an event.
* State allows an object to alter its behavior when its internal state changes.
* Strategy allows one of a family of algorithms to be selected on-the-fly at runtime.
* Template method defines the skeleton of an algorithm as an abstract class, allowing its subclasses to provide concrete behavior.

What is Singleton Design Pattern?


The Singleton Design Pattern is a Creational type of design pattern which assures to have only a single instance of a class, as it is necessary sometimes to have just a single instance.The examples can be print spooler,database connection or window manager where you may require only a single object.

In a Singleton design pattern,there is a public, static method which provides an access to single possible instance of the class.The constructor can either be private or protected.

public class SingletonClass {
private static SingletonClass instance = null;
protected SingletonClass() {
// can not be instantiated.
}
public static SingletonClass getInstance() {
if(instance == null) {
instance = new SingletonClass();
}
return instance;
}
}

In the code above the class instance is created through lazy initialization,unless getInstance() method is called,there is no instance created.This is to ensure that instance is created when needed.


public class SingletonInstantiator {
public SingletonInstantiator() {
SingletonClass instance = SingletonClass.getInstance();
SingletonClass anotherInstance =
new SingletonClass();
...
}
}

In snippet above anotherInstance is created which is a perfectly legal statement as both the classes exist in the same package in this case 'default', as it is not required by an instantiator class to extend SingletonClass to access the protected constructor within the same package.So to avoid even such scenario, the constructor could be made private.

What is difference between Abstract Factory and Factory Method design patterns?


In order to answer this question we must first understand what are Abstract Factory and Factory Method design patterns.

An Abstract Factory(AF) provides an interface for creating families of related or dependent objects without specifying their concrete classes. you usually have multiple factory implementations. Each factory implementation is responsible for creating objects that are usually in a related hierarchy.

In case of Factory Method(or simply called Factory pattern), generally a key or parameter is provided and method obtains an object of that type.The classic example can be creating a Database Connection Factory which is responsible for providing a vendor specific database connection objects(like Oracle,DB2,MS SQL Server etc.) depending upon the kind of parameter is provided.

AF is very similar to the Factory Method pattern.One difference between the two is that with the Abstract Factory pattern, a class delegates the responsibility of object instantiation to another object via composition whereas the Factory Method pattern uses inheritance and
relies on a subclass to handle the desired object instantiation.

The best example to quote of AF is EJBHome object.When a client composes the home interface and calls a create method to get the component interface. The component interface is the abstract product and the implementation is created by the container. The client composes the abstract factory (home interface) and calls a create method on the abstract factory to create the product.

In nutshell, AF is a creational pattern for the family of objects, whereas the factory method is a way to get one individual member of a family.So in a way, AF uses Factory method.


Explain Adapter Design Pattern in Java

Adapter design pattern lets unrelated classes communicate and work with each other.It achieves this objective by creating new interfaces for creating compatibility amongst otherwise non communicable classes.

The adapter classes in Java API are WindowAdapter,ComponentAdapter, ContainerAdapter, FocusAdapter, KeyAdapter, MouseAdapter and MouseMotionAdapter.

In case of listener interfaces,whenever a class implements such an interface, one has to implement all of the seven methods.In case of WindowListener interface,it has seven methods.WindowAdapter class implements WindowListener interface and make seven empty implementation. When a class subclasses WindowAdapter class, one may choose the implementation of a method as per one's choice of implementation.

Adapter design pattern is also referred as Wrapper pattern when it is introduced by composition of classes.

Explain Decorator Design Pattern in Java

Decorator design pattern attaches additional responsibilities or functions, dynamically or statically on an object.One can add new functionalities on an object without affecting other objects enhancing flexibility of an object.

The best example of Decorator pattern in a visual manner can be illustrated from JScrollPane object which can be used to decorate a JTextArea object or a JEditorPane object. The different borders of a window like BevelBorder, CompoundBorder, EtchedBorder TitledBorder etc. are other examples of classes working as decorators existent in Java API.

Decorator pattern can be used in a non-visual fashion. For example, BufferedInputStream, DataInputStream, and CheckedInputStream are decorating objects of FilterInputStream class. These decorators are standard Java API classes.

No comments:

Books

  • Hibernate in Action
  • Spring in Action