Kody źródłowe/Prototyp (wzorzec projektowy)

Z Wikibooks, biblioteki wolnych podręczników.
Przejdź do nawigacji Przejdź do wyszukiwania
Prototyp (wzorzec projektowy)
Kod źródłowy
Kody źródłowe programów stosujących wzorzec projektowy prototypu
Wikipedia
Zobacz w Wikipedii hasło Prototyp


C#[edytuj]

/*
 * Base class for all prototypes
 */
public abstract class PrototypeBase : ICloneable {
    // cloning the prototype into a new instance
    public abstract object Clone();
    // some useful action
    public abstract void Action();
}// class PrototypeBase

/*
 * Place where prototypes are cloning
 */
public class PrototypeManager {
    Dictionary<string, PrototypeBase> prototypes = new Dictionary<string,PrototypeBase>();

    //
    // manage prototype list
    //

    public void AddPrototype(string name, PrototypeBase prototype) {
        prototypes[name] = prototype;
    }// AddPrototype()

    public void DelPrototype(string name) {
        prototypes.Remove(name);
    }// DelPrototype()

    public void DropAllPrototypes() {
        prototypes.Clear();
    }// DropAllPrototypes()

    //
    // main function of class
    //

    public PrototypeBase GetCopy(string name) {
        if (prototypes.ContainsKey(name))
            return (PrototypeBase)prototypes[name].Clone(); else
            return null;
    }// GetCopy()

}// class PrototypeManager

/*
 * Concrete Prototype First
 */
public class PrototypeFirst : PrototypeBase {
    public List<string> manyStrings = new List<string>();
    //
    // cloning the prototype into a new instance
    //
    public override object Clone() {
        // kind of a deep copy
        PrototypeFirst newObj = new PrototypeFirst();
        foreach(string str in manyStrings)
            newObj.manyStrings.Add( String.Copy(str) );
        return newObj;
    }// Clone()
    //
    // useful action
    //
    public override void Action() {
        foreach (string str in manyStrings)
            Console.WriteLine(str);
    }// Action()
}// class PrototypeFirst

/*
 * Concrete Prototype Second
 */
public class PrototypeSecond : PrototypeBase {
    public int value = 0;
    //
    // cloning the prototype into a new instance
    //
    public override object Clone() {
        PrototypeFirst newObj = (PrototypeFirst)this.MemberwiseClone();
        return newObj;
    }// Clone()
    //
    // useful action
    //
    public override void Action() {
        Console.WriteLine(value);
    }// Action()
}// class PrototypeSecond

/* ------------------------------- */

/*
 * Usage example
 */
public class Usage {
    public void Foo() {
        PrototypeManager manager = new PrototypeManager();

        //
        // Filling prototype list
        //
        PrototypeFirst first = new PrototypeFirst();
        first.manyStrings.Add("String 1");
        first.manyStrings.Add("String 2");
        manager.AddPrototype("first", first);

        PrototypeSecond second = new PrototypeSecond();
        second.value = 10;
        manager.AddPrototype("second", second);

        //
        // Getting copy by prototype
        //
        PrototypeBase foo1 = manager.GetCopy("first");
        foo1.Action();

    }// Foo()
}// class Usage


C++[edytuj]

#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[edytuj]

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[edytuj]

/** 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[edytuj]

    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()

PHP[edytuj]

<?php
abstract class Prototype
{
    protected $name;
 
    public function __construct($name) 
    {
        $this->name = $name;
    }
    
    abstract function __clone();
    
    public function getName() 
    {
        return $this->name;
    }
}
 
class ConcretePrototype extends Prototype
{
    public function __construct($name) 
    {
        parent::__construct($name);
    }
    
    public function __clone() {}
}


Ten tekst nie jest objęty majątkowymi prawami autorskimi lub prawa te wygasły. Jest zatem w domenie publicznej.