-
Notifications
You must be signed in to change notification settings - Fork 0
Prototype

Creational pattern.
Provides an interface for creating copies of existing objects. Instances of classes, that implement this interface, should return copy of themself upon that call. Object, that is returned by this call, is usually hidden behind some abstract interface.
Advantages:
+ Allows to copy existing object without knowing their concrete class (might be hidden behind interface or abstract class) or how they were created.
+ Sometimes it is easier to copy existing object than creating a new instance. Object creation could be very expensive operation if things like database querying or maybe file system access are involved in it. In these cases one predefined object could serve as a template (prototype) for creating new ones.
+ In case if object of some class can only have some limited amount of states - it might be easier to instantiate objects, that represent these states and store them somewhere returning appropriate one upon client's call.
Disadvantages:
- It might be a tough task to implement deep prototyping mechanism for objects with complex structure (e.g. that store collections, other complex objects and so on)
At this project we have the following model:
Shape - interface, that has only one method called copy, which returns copy of underlying object upon call.
Shape interface is implemented by three classes:
- Circle - representation of circle shape.
- Square - representation of square shape.
- Rectangle - representation of rectangle shape.
ShapesTemplatesFactory - class, that is responsible for creating new instances of shapes, based on given templates.
Upon creating new ShapesTemplatesFactory user passes templates for Square, Rectangle and Circle to factory via constructor. Later on these objects are used as templates for creating new instances of these shapes. Has three methods:
-
buildSquare : Square - returns object, based on squareTemplate via squareTemplate.copy() method call.
-
buildRectangle : Rectangle - returns object, based on rectangleTemplate via rectangleTemplate.copy() method call.
-
buildCircle : Circle - returns object, based on circleTemplate via circleTemplate.copy() method call.
ShapeEditorClient - class, that performs some portion of work, using prototypes from ShapesTemplatesFactory. In our case it builds the following shapes:
- big red circle
- medium green square
- small blue rectangle
As it can be seen, instead of creating new object every time, this client operates on ShapesTemplatesFactory, which returns copies of predefined objects.
Even though it is a very simple example, it demonstrates basic concepts of Prototype pattern usage.