Sunday, March 21, 2010

Prototype

Allows object to be created without knowing their exact class or details of how to create them.

Factory

Defines an interface for creating an object, but let the subclasses decide which class to instantiate (defer instantiation to subclasses, without knowing the the specific class being instantiated). This enables to introduce new classes without modifying the code

Benefits:
  • Eliminates the need to bind application classes into your code (Code deals only with interfaces)
  • Enables the subclasses to provide an extended version of an object, because creating object inside a class is more flexible than creating object directly in the client

When to use:
  • A class cannot anticipate the class of objects it must create
  • A class wants its subclasses to specify the objects it creates
  • Classes delegate responsibility to one of several helper subclasses, and you want to localise the knowledge of which helper subclass is the delegate.

Builder pattern

Separates the construction of complex object from its representation so the same construction process can create different objects.

Builder allows client to construct complex object by specifying only its type and content. The client is shielded from the details of the construction.

The builder pattern produces only one main product, but there might be more then one class in that product, but there is always one main product.

When builder is used, the complex object should be created one step at a time, other patterns build the objects in a single step. Example

buildAddress();
buildContactDetails();
buildChildren();
getResult();

Benefits:
  • Let you vary product's internal representation
  • Isolates code construction and representation
  • Gives greater control over the construction process
  • Building process can be easily tested and verified (from me)
When to use:
  • The algorithm for creating a complex object should be independent of both the parts the make up the product and how these parts are assembled.
  • The construction process must allow different representations of the constructed object

Abstract Factory

Provides interface for creating families or related or dependent objects without specifying their concrete classes

Benefits:
  • Isolates concrete classes from client
  • Allows for exchanging product families easy
  • Promotes consistency among products
When to use:
  • The system should be independent of how its products are created.
  • The system should be configured with one of multiple families of products, like MS, Apple, Linux
  • The family or related objects are designed to be used together, and this constraint must be enforced, this is the key point of Abstract Factory.
  • You want to reveal only the interfaces, not the implementation of a library