The Prototype Design Pattern
The Prototype Pattern specify the objects to create using a prototypical instance and creates new objects by copying this prototype.
Prototype Pattern : Definition
The prototype pattern specifies the kind of objects to create using a prototypical instance, and new objects are created by copying this prototype.
Participants
Prototype : declares an interface for cloning itself.
Concrete Prototype : implements an operation for cloning itself. ?
Client : creates a new object by asking a prototype to clone itself and then making required modifications.
Prototype Pattern: Implementation
To implement the pattern, declare an abstract base class that specifies a pure virtual clone() method. ?
Any class that needs a "polymorphic constructor" capability derives itself from the abstract base class and implements the clone() operation.
Clone can be implemented either as a deep copy or a shallow copy:
?? In a deep copy, all objects are duplicated,
?? In a shallow copy, only the top-level objects are duplicated, and the lower levels contain references. ?
?Prototype Pattern: Structural Code
/**
*?? Test driver for the pattern.
*/ public class Test { public static void main(
String arg[] ) {
Client client = new Client();
Prototype copy = client.operation(); ?
}
}
/**
*?? Declares an interface for cloning itself.
*/
public interface Prototype
{ Prototype copy(); }
/**
领英推荐
*?? Implements an operation for cloning itself.
*/ public class ConcretePrototype1 implements Prototype { private String state1 = "Blueprint"; private Prototype state2; public Prototype copy(){
ConcretePrototype1 duplicate = new
ConcretePrototype1(); duplicate.setState1( new String( state1 )); if( state2 != null ){ duplicate.setState2( state2.copy() ); } return duplicate;
} void setState1( String state
) { state1 = state; } void setState2( Prototype state ){ state2 = state;
}
}
/**
* Creates a new object by asking a prototype to clone itself.
*/ public class Client { public
Prototype operation() {
Prototype prototype = new
ConcretePrototype1(); Prototype copy = prototype.copy(); return copy;
}
}
Benefits, Uses and Drawbacks ?
?
?Benefits
Hides the complexities of making new instances from the client,
Provides the option for the client to generate objects whose type is not known,
??In some circumstances, copying an object can be more efficient than creating a new object.
?
?Uses
Prototypes should be considered when a system must create new objects of many types in a complex class hierarchy. ?
?
Drawbacks
A drawback to using the Prototype is that making a copy of an object can sometimes be complicated.
?
?
?