Specify kind of objects to create using a prototypical instance, and create new objects by copying this prototype.
Use the Prototype pattern when a system should be independent of how its products are created, composed, and represented; and
- When the classes to instantiate are specified at the run-time, for example, by dynamic loading;
- To avoid building a class hierarchy of factories that parallels the class hierarchy of products.
- when instances of a class can have one of only few different combinations of state.It may be more convient to install a corresponding number of protypes and clone them rather instantiating the class manually, each time with appropiate state.
Prototype has many of the same consequences that Abstract Factory and Builder have. It hides the concrete product classes from the client, thereby reducing the number of names clients know about. Moreover, these patterns let a client work with application specific classes without modification.
Additional benifits of the Prototype patterns are listed below.
- Adding and removing products at run time. Prototype let you incorporate a new concrete product class into a system simply by registering a prototypical instance with the client. That’s a bit more flexible than other creational patterns, because a client can install and remove prototypes at run-time.
- Specifying new objects by varying values. Highly dynamic systems let you define new behaviour through object composition – by specifying values for an object’s variable. For example – and not by defining new classes. You effectively define new kinds of objects by instantiating existing classes and registering the instance as prototypes of client objects.
- Specifying new objects by varying structure. Many applications build objects from parts and subparts. Editors for circuit design, for example, build circuits out of subcurcuits. For convience, such application often let you instantiate complex, user-defined structure. say, to use specific subcurcuits again and again.
The main liability of the prototype pattern is that each subclass of Prototype must implement the Clone operation, which may be difficult. For example, adding Clone can be difficult when the classes under consideration already exist. Implementing Clone can be difficult when their internals include objects that don’t support copying or have circular references.