Monday, August 21, 2006

Design Patterns


Abstract Factory
- Use while creating dependent or related objects
- Better than using different constructors
- Use when do not know what type to construct exactly
- Uses abstract,virtual methods to return abstract classes or interfaces

Builder
- Encapsulate the construction of objects.
- Use while creating complex objects. Specify the type and hide details of the construction.
- Split the contruction into steps gaining more control of it instead of creating it at once.
- Similar to the factory classes but creates objects in more than one step.

Factory
- Subclasses decide which class to instantiate
- If you have objects that have common characteristics.
- If you are creating a class which is inherited from an interface and you have also other classes inherited from the same interface, the class that you are using to create objects is a factory class
- Uses abstract methods to return class types.
- It is common to use static factory methods.
- Creates objects in one step.
.NET ex: Convert.ToBoolean(aString)

Prototype
- Create a prototype object to create other objects by copying it.
.NET ex: Inherit the prototype class from IClonable interface and implement both Shallow and DeepCopy methods in the Clone method. Use MemberwiseClone method for the shallow copying. For deep copying, serialize the object and return an object which is the deserialized form.

Singleton
- Ensure that you have only one instance (Instantiation control) at a time and it is provided globally (Global access).

.NET Ex:
>public sealed class SingletonClass{
>>>private static readonly SingletonClass instance = new SingletonClass();
>>>private Singleton(){}
>>>public static SingletonClass SingletonInstance{
>>>>>>get{
>>>>>>>>>return instance;
>>>>>>}
>>>}
>}
- Thread safety is guaranteed by the compiler.
- The instance is created the first time any member of the class is referenced(Lazy loading).
- The class is marked as sealed to prevent derivation, hence adding new instances.
- The variable is marked as read-only: It can only be assigned during static inialization or in a class contructor.
- The contsructor is marked as private: Cannot be instantiated outside of the class itself.

Adapter
- Converts the interface of a class into another class helping the client to be able work with the expected interface.
- Especially useful while developing with 3rd party components, developing applications to work with existing components, integrations applications.
- Use to provide mapping between classes
.NET Ex: Runtime Callable Wrappers to work with COM components

Bridge
- Decouples an abstraction from its implementation.
- Decouples the two end of an application (Client and the servicing part) so that two can vary independently
- Simple business data layer pattern can be an example. Business layer has higher level methods.
If the business layer is written using an interface which the data access layer is inherited, data layer methods can be changed without changing the business layer method and effecting clients at all. This pattern hence hides the implementation of concrete data classes.

Composite
- Use while dealing with hierarchical objects
- Define leaf and branch nodes which are inherited from the same interface
Ex: Tree control

Decorator
- Extends an object's behaviour dynamically
- Wraps itself around the original class. Original class is usually passed as a parameter in the constructor.
- Usually, calls are passed to the original class and extra functionality is assed based on the results.
- Decorator class is inherited from the same base class as the original class hence can be called in the same way as the original class .
.NET Ex: BufferedStreamReader and Stream classes

Facade
- High level interface for the subsystems hence making a complex system easy to use for clients.
- Calls made by the client are passed to appropriate subsystems
- Exposes only the methods that need to be known by clients.
Ex: web Services, Service Oriented Architectures, Service layers between the presentation layers and the business classes
.NET Ex: SmtpMail class

FlyWeight
- Uses sharing to support large number of fine grained objects efficiently.
- Flyweights objects are immutable.
- Used in memory management techniques
- Usually used with Factory classes. Factory classes create the Flyweight objects. Other classes request the flyweight objects from a factory class.

Proxy
- Provides a place holder for another object to control access to it. It may be responsible for the creation and deletion of the main object.
- It can be used instead of the main object since it has the same interface and the clients may not know they are dealing with a proxy
- It may be responsible to communicate with a main object in a different domain
.NET Ex: Remoting: When an object is needed a proxy is created to send the request to the remote object

Chain of Responsibility
- Request is passed through a number of handler objects until an object handles it.
- The chain is created by several linked objects. Each object can handle the request or depending on the condition pass the request to the next handler in the chain.
- Client does not know which object in the chain can handle the request. (Loose coupling)
.NET Ex: Windows event model

Command
- Encapsulates a request or an action as an object
- Helpful in systems where undoable operations are supported. Ex: Menuing systems, word processors, databases
- All the command are inherited from the same interface having Do and Undo methods

Interpreter
- Solves the problem creating a scripting language which should be mapped to a grammar
- Enhancement of the composite pattern
Ex:http://home.earthlink.net/~huston2/ps/hanoi_article.html

Iterator
- Traverses through a collection of items without exposing its underlying representation
- Seperates the collection of objects from the traversal of these objects
- The collection may be an array, a list, a tree, a graph and must implement IEnumerable interface

Mediator
- Coordinates objects encapsulating the interaction between them. All the interaction goes through the mediator.
- Facilitates closely coupled communication between different objects and object types.
- Each object knows its mediator, and the mediator knows its objects to mediate
- Useful when the objects need to know the every state change of other objects
- Use the mediator pattern when a central authority is needed over a group of objects
Ex: Chat applications

Memento
- Helps to restore an object’s previous state. Provides storage and restoration.
- An object passes a snapshot of its state to the mediator to store its current state. The object may be marked as serializable hence providing the exact state as it was before
- Memento object should be kept by another object.
Ex: Implementing undo operations in a database. Can be combined with the Command pattern to provide undo facility.
.NET Ex: Serialization

Observer
- Provides a one-to-many dependency between objects. When one object changes its state, all its dependents are notified and updated automatically.
- The object that changes its state sends a notification to its observers, the observer then updates the other objects
- Promotes loose coupling
.NET Ex: Delegates Events: Subjects, Delegates: Observers

State
- Allows an object to behave differently depending on its internal state
- All the state classes are inherited form one interface and each of them implements a behaviour associated with a particular state
- State is changed by the state classes if it needs to
- Instead of if case statements, it relies on polymorphism
Ex: Workflow systems

Strategy
- Use this pattern to deal with a family of algorithms encapsulating each of them in an object. So that clients can change its strategies dynamically.
- Each strategy object is inherited form the same interface.
- Plug and play pattern. The method that is called by the client can be changed with any of the other Strategy class
- Provides extensibility and customization
.NET Ex: Delegates can also be used as a strategy pattern. ArrayList.Sort works on IComparer interface. Any class that implements this interface is basically a strategy class.

Template
- Defines an algorithm but some steps are deferred to the subclasses to be implemented.
- Skelton of an algorithm is defined.
- Derived classes have the option to redefine or adjust certain steps
- Provides extensibility and customization
- Based on object inheritance. Microsoft append Core keyword to its virtual methods in the control classes allowing them to be overridden in the derived classes
Ex: Implementing an abstract class with some of the methods implemented and some are called in the class but not implemented as they are deferred to the derived classes for the implementation.

Visitor
- Useful when a functional change is required to a collection of class.
- Defines a new operation without changing the hierarchy
- Developer must have written its classes to accept visitor classes anticipating functional adjustments may occur in future