A prototype pattern is a creational design pattern used in software development 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.

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.

The client, instead of writing code that invokes the "new" operator on a hard-wired class name, calls the clone() method on the prototype, calls a factory method with a parameter designating the particular concrete derived class desired, or invokes the clone() method through some mechanism provided by another design pattern.

Contents

C++ Sample code

#include <iostream>
#include <map>
#include <string>
#include <cstdint>
 
using namespace std;
 
enum RECORD_TYPE_en
{
  CAR,
  BIKE,
  PERSON
};
 
/**
 * Record is the Prototype
 */
 
class Record
{
  public :
 
    Record() {}
 
    virtual ~Record() {}
 
    virtual Record* Clone() const=0;
 
    virtual void Print() const=0;
};
 
/**
 * CarRecord is Concrete Prototype
 */
 
class CarRecord : public Record
{
  private :
    string m_oStrCarName;
 
    uint32_t m_ui32ID;
 
  public :
 
    CarRecord(const string& _oStrCarName, uint32_t _ui32ID)
      : Record(), m_oStrCarName(_oStrCarName),
        m_ui32ID(_ui32ID)
    {
    }
 
    CarRecord(const CarRecord& _oCarRecord)
      : Record()
    {
      m_oStrCarName = _oCarRecord.m_oStrCarName;
      m_ui32ID = _oCarRecord.m_ui32ID;
    }
 
    ~CarRecord() {}
 
    CarRecord* Clone() const
    {
      return new CarRecord(*this);
    }
 
    void Print() const
    {
      cout << "Car Record" << endl
        << "Name  : " << m_oStrCarName << endl
        << "Number: " << m_ui32ID << endl << endl;
    }
};
 
 
/**
 * BikeRecord is the Concrete Prototype
 */
 
class BikeRecord : public Record
{
  private :
    string m_oStrBikeName;
 
    uint32_t m_ui32ID;
 
  public :
    BikeRecord(const string& _oStrBikeName, uint32_t _ui32ID)
      : Record(), m_oStrBikeName(_oStrBikeName),
        m_ui32ID(_ui32ID)
    {
    }
 
    BikeRecord(const BikeRecord& _oBikeRecord)
      : Record()
    {
      m_oStrBikeName = _oBikeRecord.m_oStrBikeName;
      m_ui32ID = _oBikeRecord.m_ui32ID;
    }
 
    ~BikeRecord() {}
 
    BikeRecord* Clone() const
    {
      return new BikeRecord(*this);
    }
 
    void Print() const
    {
      cout << "Bike Record" << endl
        << "Name  : " << m_oStrBikeName << endl
        << "Number: " << m_ui32ID << endl << endl;
    }
};
 
 
/**
 * PersonRecord is the Concrete Prototype
 */
 
class PersonRecord : public Record
{
  private :
    string m_oStrPersonName;
 
    uint32_t m_ui32Age;
 
  public :
    PersonRecord(const string& _oStrPersonName, uint32_t _ui32Age)
      : Record(), m_oStrPersonName(_oStrPersonName),
        m_ui32Age(_ui32Age)
    {
    }
 
    PersonRecord(const PersonRecord& _oPersonRecord)
      : Record()
    {
      m_oStrPersonName = _oPersonRecord.m_oStrPersonName;
      m_ui32Age = _oPersonRecord.m_ui32Age;
    }
 
    ~PersonRecord() {}
 
    Record* Clone() const
    {
      return new PersonRecord(*this);
    }
 
    void Print() const
    {
      cout << "Person Record" << endl
        << "Name : " << m_oStrPersonName << endl
        << "Age  : " << m_ui32Age << endl << endl ;
    }
};
 
 
/**
 * RecordFactory is the client
 */
 
class RecordFactory
{
  private :
    map<RECORD_TYPE_en, Record* > m_oMapRecordReference;
 
  public :
    RecordFactory()
    {
      m_oMapRecordReference[CAR]    = new CarRecord("Ferrari", 5050);
      m_oMapRecordReference[BIKE]   = new BikeRecord("Yamaha", 2525);
      m_oMapRecordReference[PERSON] = new PersonRecord("Tom", 25);
    }
 
    ~RecordFactory()
    {
      delete m_oMapRecordReference[CAR];
      delete m_oMapRecordReference[BIKE];
      delete m_oMapRecordReference[PERSON];
    }
 
    Record* CreateRecord(RECORD_TYPE_en enType)
    {
      return m_oMapRecordReference[enType]->Clone();
    }
};
 
int main()
{
  RecordFactory* poRecordFactory = new RecordFactory();
 
  Record* poRecord;
  poRecord = poRecordFactory->CreateRecord(CAR);
  poRecord->Print();
  delete poRecord;
 
  poRecord = poRecordFactory->CreateRecord(BIKE);
  poRecord->Print();
  delete poRecord;
 
  poRecord = poRecordFactory->CreateRecord(PERSON);
  poRecord->Print();
  delete poRecord;
 
  delete poRecordFactory;
  return 0;
}


VB.net sample code

Public Enum RecordType
    CAR
    PERSON
End Enum
 
''
'' Record is the Prototype
''
Public MustInherit Class Record
    Public MustOverride Function Clone() As Record
End Class
 
''
'' PersonRecord is the Concrete Prototype
''
Public Class PersonRecord : Inherits Record
    Private name As String
    Private age As Byte
 
    Public Overrides Function Clone() As Record
        Return CType(Me.MemberwiseClone(), Record)  ' default shallow copy
    End Function
End Class
 
''
'' CarRecord is another Concrete Prototype
''
Public Class CarRecord : Inherits Record
    Private carname As String
    Private id As Guid
 
    Public Overrides Function Clone() As Record
        Dim myClone As CarRecord = CType(Me.MemberwiseClone(), Record)  ' default shallow copy
        myClone.id = Guid.NewGuid()  ' always generate new id
        Return myClone
    End Function
End Class
 
''
'' RecordFactory is the client
''
Public Class RecordFactory
    Private Shared _prototypes As New Generic.Dictionary(Of RecordType, Record)
 
    '' Constructor
    Public Sub RecordFactory()
        _prototypes.Add(RecordType.CAR, New CarRecord())
        _prototypes.Add(RecordType.PERSON, New PersonRecord())
    End Sub
 
    '' The Factory method
    Public Function CreateRecord(ByVal type As RecordType) As Record
        Return _prototypes(type).Clone()
    End Function
End Class

Java sample code

/** Prototype Class **/
public class Cookie implements Cloneable {
 
   public Object clone() {
      try {
         Cookie copy = (Cookie)super.clone();
 
         //In an actual implementation of this pattern you might now change references to
         //the expensive to produce parts from the copies that are held inside the prototype.
 
         return copy;
 
      }
      catch(CloneNotSupportedException e) {
         e.printStackTrace();
         return null;
      }
   }
}
 
/** Concrete Prototypes to clone **/
public class CoconutCookie extends Cookie { }
 
/** Client Class**/
public class CookieMachine {
 
   private Cookie cookie;//could have been a private Cloneable cookie; 
 
   public CookieMachine(Cookie cookie) { 
      this.cookie = cookie; 
   } 
   public Cookie makeCookie() { 
      return (Cookie)cookie.clone(); 
   } 
   public static void main(String args[]) {
      Cookie tempCookie =  null; 
      Cookie prot = new CoconutCookie(); 
      CookieMachine cm = new CookieMachine(prot); 
      for (int i=0; i<100; i++) 
         tempCookie = cm.makeCookie(); 
   } 
}

Python

    from copy import deepcopy
 
    class Prototype:
        def __init__(self):
           self._objs = {}
 
        def registerObject(self, name, obj):
           """
           register an object.
           """
           self._objs[name] = obj
 
        def unregisterObject(self, name):
           """unregister an object"""
           del self._objs[name]
 
        def clone(self, name, **attr):
           """clone a registered object and add/replace attr"""
           obj = deepcopy(self._objs[name])
           obj.__dict__.update(attr)
           return obj
 
######## “create another instance, w/state, of an existing instance of unknown class/state”
 
    from copy import deepcopy, copy
 
    g = Graphic() # non-cooperative form
    shallow_copy_of_g = copy(g)
    deep_copy_of_g = deepcopy(g)
 
    from copy import deepcopy, copy
 
    class Graphic:
        def clone(self):
           return copy(self)
    g = Graphic() # cooperative form
    copy_of_g = g.clone()

Examples

The Prototype pattern specifies the kind of objects to create using a prototypical instance. Prototypes of new products are often built prior to full production, but in this example, the prototype is passive and does not participate in copying itself. The mitotic division of a cell - resulting in two identical cells - is an example of a prototype that plays an active role in copying itself and thus, demonstrates the Prototype pattern. When a cell splits, two cells of identical genotype result. In other words, the cell clones itself. [Michael Duell, "Non-software examples of software design patterns", Object Magazine, Jul 97, p54]

Rules of thumb

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)

Often, designs start out using Factory Method (less complicated, more customizable, subclasses proliferate) and evolve toward Abstract Factory, Prototype, or Builder (more flexible, more complex) as the designer discovers where more flexibility is needed. (GoF, p136)

Prototype doesn't require subclassing, but it does require an "initialize" operation. Factory Method requires subclassing, but doesn't require initialization. (GoF, p116)

Designs that make heavy use of the Composite and Decorator patterns often can benefit from Prototype as well. (GoF, p126)

The rule of thumb could be that you would need to clone() an Object when you want to create another Object at runtime which is a true copy of the Object you are cloning. True copy means all the attributes of the newly created Object should be the same as the Object you are cloning. If you could have instantiated the class by using new instead, you would get an Object with all attributes as their initial values. For example, if you are designing a system for performing bank account transactions, then you would want to make a copy of the Object which holds your account information, perform transactions on it, and then replace the original Object with the modified one. In such cases, you would want to use clone() instead of new.

Cloning in PHP

In PHP 5, unlike previous versions, objects are by default passed by reference. In order to pass by value, use the "magic function" __clone(). This makes the prototype pattern very easy to implement. See object cloning for more information.

References


No comments have been added.



Your name:

City:

Country:

Your comments:

Security check *
(Please enter the number into adjoining box)