Monday 14 April 2014

Creational Design Patterns -> Prototye pattern

Motivation:
Cost is important, If the cost of creating a new object is large and creation is resource intensive, we clone the object. This pattern is used 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.


Intent:

·         specifying the kind of objects to create using a prototypical instance
·         creating new objects by copying this prototype
Use when:

Classes to be created are specified at runtime.
  •  Only a limited number of state combinations exist in an object.
  •  Objects or object structures are required that are identical or closely resemble other existing objects or object structures.
  •  The initial creation of each object is an expensive operation.



Interesting points:
Sometimes creational patterns overlap — there are cases when either Prototype or Abstract Factory would be appropriate. At other times they complement each other: Abstract Factory might store a set of Prototypes from which to clone and return product objects (GoF, p126). Abstract Factory, Builder, and Prototype can use Singleton in their implementations. (GoF, p81, 134). Abstract Factory classes are often implemented with Factory Methods (creation through inheritance), but they can be implemented using Prototype (creation through delegation). (GoF, p95)

Advantages:

  • Hides complexities of creating of objects.
  • The clients can get new objects without knowing whose type it will be.
  • Reduces subclassing.


Disadvantages:

  • Sometimes making a object copy shall become complicated
  • Classes that have circular references to other classes cannot really be cloned.
Sources: Wikipedia, OODesign, TutorialsPoint, Javarevisited

No comments:

Post a Comment