The original model mode belongs to the object creation mode. A prototype object is provided to specify the type of the object to be created, and more objects of the same type are created by copying the prototype object.
The original model has two forms: simple form and registration form.
Simple Form of original model class diagram:
Source code:
Public interfacePrototypeExtends cloneable {
Object clone ();
}
Public classConcreteprototypeImplements prototype {
Public object clone ()
{
System. Out. println ("return New concreteprototype ()");
Return new concreteprototype ();
}
}
Public classClient{
Public static void main (string [] ARGs ){
Prototype theprototype = new concreteprototype ();
Prototype pt1 = (prototype) theprototype. Clone ();
}
}
Original Model pattern class diagram in registration form:
Where:
Prototypemanager) Role: Create an object for a specific prototype and record each created object.
Source code:
Public interfacePrototypeExtends cloneable {
Object clone ();
}
Public classConcreteprototypeImplements prototype {
Public object clone ()
{
Return new concreteprototype ();
}
}
Public classPrototypemanager{
Private vector arrprototype = new vector ();
Public void addprototype (prototype pt)
{
Arrprototype. Add (PT );
}
Public prototype getprototype (INT index)
{
Return (prototype) arrprototype. Get (INDEX );
}
Public int getsize ()
{
Return arrprototype. Size ();
}
}
Public classClient{
Public static void main (string [] ARGs ){
Prototypemanager Mgr = new prototypemanager ();
Prototype theprototype = new concreteprototype ();
Prototype pt1 = (prototype) theprototype. Clone ();
Prototype pt2 = (prototype) theprototype. Clone ();
Mgr. addprototype (pt1 );
Mgr. addprototype (pt2 );
System. Out. println ("" + Mgr. getsize ());
}
}
Two forms of comparison:
If the number of prototype objects to be created is small and relatively fixed, use the original prototype mode in simple form. If the number of prototype objects to be created is not fixed, use the original model mode in the registration form.
Comparison of three common creation modes:
The builder mode focuses on step-by-step creation of complex objects (objects are not directly returned). The abstractfactory mode focuses on generating multiple dependent classes, while the prototype mode focuses on copying itself to create new classes.