Design Patterns

Saturday, June 27, 2009

Design Patterns:

It is a general reusable solution to a commonly occurring problem in software design , description or template for how to solve a problem that can be used in many different situations.

Use of Design Patterns:

  • Design patterns can speed up the development process by providing tested, proven development paradigms.
  • New Designs are not visible until later in the implementation, Reusing of Design patterns help to prevent this.
Classification of Design patterns:
  • Creational Pattern
  • Structural Pattern
  • Behavioral Pattern
  • Concurrency Pattern
Typical Creational Patterns:
  1. Abstract Factory
  2. Factory method
  3. Builder
  4. Lazy initialization
  5. Object pool
  6. Prototype
  7. Singleton
  8. Multiton
  9. Resource acquisition
1. Abstract Factory Pattern:

It provides a way to encapsulate a group of individual Factory that have a common theme.
Provide an interface for creating families of related or dependent objects without specifying their concrete classes.
Example :

diagramFactory --> Round , Triangle , Line
DocumentFactory --> Letter , email, eBook

2.
Factory method Pattern:
Define an interface for creating an object, but let subclasses decide which class to instantiate. Factory Method lets a class defer instantiation to subclasses.
The factory method pattern is an object-oriented design pattern. It deals with the problem of creating objects without specifying the exact class of object that will be created. The factory method design pattern handles this problem by defining a separate method for creating the objects, whose subclasses can then override to specify the derived type of product that will be created.

Example:
ConcreteCreator Inherits Creator; Both will have method factoryMethod () Returns Product.

3. Builder Pattern:
Separate the construction of a complex object from its representation so that the same construction process can create different representations.

The Builder Pattern is a software design pattern. The intention is to abstract steps of construction of object so that different implementations of these steps can construct different representations of objects. Often, the Builder Pattern is used to build Products in accordance to the Composite pattern, a structure pattern.

4.
Lazy initialization Pattern:

In a software design pattern view, lazy initialization is often used together with a factory method pattern. This combines three ideas:
* using a factory method to get instances of a class (factory method pattern)
* storing the instances in a map, so you get the same instance the next time you ask for an instance with same parameter (compare with a singleton pattern)
* using lazy initialization to instantiate the object the first time it is requested (lazy initialization pattern).

5. Object pool Pattern:

An object pool is a set of initialized objects that are kept ready to use, rather than
allocated and destroyed on demand. A client of the pool will request an object from the pool and perform
operations on the returned object. When the client has finished with an object, it returns it to the pool, rather than destroying it. It is a specific type of factory object.

6.
Prototype Pattern:
Specify the kinds of objects to create using a prototypical instance, and create new objects by copying this prototype.
A prototype pattern is a creational design pattern used in software development when the type of objects to create is determined by a prototypical instance, which is cloned to produce new objects. This pattern is used to:
* avoid subclasses of an object creator in the client application, like the abstract factory pattern does.
* avoid the inherent cost of creating a new object in the standard way (e.g., using the 'new' keyword) when it is prohibitively expensive for a given application.

7. Singleton pattern:
The singleton pattern is a design pattern that is used to restrict instantiation of a class to one object.
Ensure a class has only one instance, and provide a global point of access to it.
Example: Only one instance of a database Object

8. Multiton Pattern:
The Multiton pattern expands on the Singleton concept to manage a map of named instances as key-value pairs.
Example: Java Runtime java.lang.runtime

9.
Resource acquisition Pattern:
It is initialization Ensure that resources are properly released by tying them to the lifespan of suitable objects.

Structural Patterns:

Adapter :Convert the interface of a class into another interface clients expect. Adapter lets classes work together that couldn't otherwise because of incompatible interfaces.
Bridge: Decouple an abstraction from its implementation so that the two can vary independently.
Composite: Compose objects into tree structures to represent part-whole hierarchies. Composite lets clients treat individual objects and compositions of objects uniformly.
Decorator : Attach additional responsibilities to an object dynamically keeping the same interface. Decorators provide a flexible alternative to subclassing for extending functionality.
Facade : Provide a unified interface to a set of interfaces in a subsystem. Facade defines a higher-level interface that makes the subsystem easier to use.
Flyweight: Use sharing to support large numbers of fine-grained objects efficiently.
Proxy : Provide a surrogate or placeholder for another object to control access to it.

Behavioral Patterns:

Behavioral design patterns are design patterns that identify common
communication patterns between objects and realize these patterns.
By doing so, these patterns increase flexibility in carrying out this communication.

* Chain of responsibility pattern: Command objects are handled or passed on to other objects by logic-containing processing objects
* Command pattern: Command objects encapsulate an action and its parameters
* Interpreter pattern: Implement a specialized computer language to rapidly solve a specific set of problems
* Iterator pattern: Iterators are used to access the elements of an aggregate object sequentially without exposing its underlying representation
* Mediator pattern: Provides a unified interface to a set of interfaces in a subsystem
* Memento pattern: Provides the ability to restore an object to its previous state (rollback)
* Null Object pattern: designed to act as a default value of an object
* Observer pattern: aka Publish/Subscribe or Event Listener. Objects register to observe an event which may be raised by another object
* State pattern: A clean way for an object to partially change its type at run time
* Strategy pattern: Algorithms can be selected on the fly
* Specification pattern: Recombination Business logic in a Boolean fashion
* Template method pattern: Describes the program skeleton of a program
* Visitor pattern: A way to separate an algorithm from an object
* Single-serving visitor pattern: Optimize the implementation of a visitor that is allocated, used only once, and then deleted
* Hierarchical visitor pattern: Provide a way to visit every node in a hierarchical data structure such as a tree.

Concurrency Pattern
Object Oriented Design patterns typically show relationships and interactions between classes & objects targeting on the Design problems rather than application problems.

concurrency patterns are those types of design patterns that deal with multi-threaded programming paradigm.

* Active Object
* Balking pattern
* Double checked locking pattern
* Guarded suspension
* Leaders/followers pattern
* Monitor Object
* Read write lock pattern
* Scheduler pattern
* Thread pool pattern
* Thread-Specific Storage
* Reactor pattern

The Active Object design pattern decouples method execution from method invocation that reside in their own thread of control. The goal is to introduce concurrency, by using asynchronous method invocation and a scheduler for handling requests.

The pattern consists of six elements:
* a proxy, which provides an interface towards clients with publicly accessible methods
* an interface which defines the method request on an active object
* a list of pending requests from clients
* a scheduler, which decides which request to execute next
* the implementation of the active object method.
* a callback or variable for the client to receive the result.

The Balking pattern is a software design pattern that only executes an action on an object when the object is in a particular state.

There are some in this field that think this is more of an Anti-Pattern, than a design pattern.
If an object cannot support its API, it should either limit the API so that the offending call is not available or it should …

* be created in a sane state
* not make itself available until it is in a sane state
* become a façade and answer back an object that is in a sane state.

Double-checked locking is a software design pattern also known as "double-checked locking optimization". The pattern is designed to reduce the overhead of acquiring a lock by first testing the locking criterion (the 'lock hint') in an unsafe manner; only if that succeeds does the actual lock proceed.

Guarded suspension is a software design pattern for managing operations that require both a lock to be acquired and a precondition to be satisfied before the operation can be executed. The guarded suspension pattern is typically applied to method calls in object-oriented programs, and involves suspending the method call, and the calling thread, until the precondition (acting as a guard) is satisfied.

In concurrent programming, a monitor is an object intended to be used safely by more than one thread. The defining characteristic of a monitor is that its methods are executed with mutual exclusion. That is, at each point in time, at most one thread may be executing any of its methods. This mutual exclusion greatly simplifies reasoning about the implementation of monitors compared with code that may be executed in parallel.

Monitors also provide a mechanism for threads to temporarily give up exclusive access, in order to wait for some condition to be met, before regaining exclusive access and resuming their task. Monitors also have a mechanism for signaling other threads that such conditions have been met.

Used in Banking Software design to avoid multiple withdraw of amount from same account.

A read/write lock pattern or simply RWL is a software design pattern that allows concurrent read access to an object but requires exclusive access for write operations.

In this pattern, multiple readers can read the data in parallel but an exclusive lock is needed while writing the data. When a writer is writing the data, readers will be blocked until the writer is finished writing.

scheduler pattern is a software design pattern. It is a concurrency pattern used to explicitly control when threads may execute single-threaded code.

The scheduler pattern uses an object that explicitly sequences waiting threads. It provides a mechanism to implement a scheduling policy, but is independent of any specific scheduling policy — the policy is encapsulated in its own class and is reusable.

In the thread pool pattern in programming, a number of threads are created to perform a number of tasks, which are usually organized in a queue. Typically, there are many more tasks than threads. As soon as a thread completes its task, it will request the next task from the queue until all tasks have been completed. The thread can then terminate, or sleep until there are new tasks available.

0 comments: