原型模式的實現完整代碼示例(code):原型模式的實現很簡單,這里為了方便初學者的學習和參考,將給出完整的實現代碼(所有代碼采用 C++實現,并在 VC 6.0 下測試運行)。
代碼片斷 1:Prototype.h
//Prototype.h#ifndef _PROTOTYPE_H_#define _PROTOTYPE_H_class Prototype{ public: virtual ~Prototype(); virtual Prototype* Clone() const = 0; protected: Prototype(); private:};class ConcretePrototype:public Prototype{ public: ConcretePrototype(); ConcretePrototype(const ConcretePrototype& cp); ~ConcretePrototype(); Prototype* Clone() const; protected: private:};#endif //~_PROTOTYPE_H_
代碼片斷 2:Prototype.cpp
//Prototype.cpp#include "Prototype.h"#include <iostream>using namespace std;Prototype::Prototype(){}Prototype::~Prototype(){}Prototype* Prototype::Clone() const{ return 0;}ConcretePrototype::ConcretePrototype(){}ConcretePrototype::~ConcretePrototype(){}ConcretePrototype::ConcretePrototype(const ConcretePrototype& cp){ cout<<"ConcretePrototype copy ..."<<endl;}Prototype* ConcretePrototype::Clone() const{ return new ConcretePrototype(*this);}
代碼片斷 3:main.cpp
//main.cpp#include "Prototype.h"#include <iostream>using namespace std;int main(int argc,char* argv[]){ Prototype* p = new ConcretePrototype(); Prototype* p1 = p->Clone(); return 0;}
代碼說明:原型模式的結構和實現都很簡單,其關鍵就是(C++中)拷貝構造函數的實現方式,這也是 C++實現技術層面上的事情。由于在示例代碼中不涉及到深層拷貝(主要指有指針、復合對象的情況),因此我們通過編譯器提供的默認的拷貝構造函數(按位拷貝)的方式進行實現。說明的是這一切只是為了實現簡單起見,也因為本文檔的重點不在拷貝構造函數的實現技術,而在原型模式本身的思想。
另一個實例
我們再來看一個具體項目的例子:
namespace Prototype_DesignPattern{ using System; // Objects which are to work as prototypes must be based on classes which // are derived from the abstract prototype class abstract class AbstractPrototype { abstract public AbstractPrototype CloneYourself(); } // This is a sample object class MyPrototype : AbstractPrototype { override public AbstractPrototype CloneYourself() { return ((AbstractPrototype)MemberwiseClone()); } // lots of other functions go here! } // This is the client piece of code which instantiate objects // based on a prototype. class Demo { private AbstractPrototype internalPrototype; public void SetPrototype(AbstractPrototype thePrototype) { internalPrototype = thePrototype; } public void SomeImportantOperation() { // During Some important operation, imagine we need // to instantiate an object - but we do not know which. We use // the predefined prototype object, and ask it to clone itself. AbstractPrototype x; x = internalPrototype.CloneYourself(); // now we have two instances of the class which as as a prototype } } /// <summary> /// Summary description for Client. /// </summary> public class Client { public static int Main(string[] args) { Demo demo = new Demo(); MyPrototype clientPrototype = new MyPrototype(); demo.SetPrototype(clientPrototype); demo.SomeImportantOperation(); return 0; } }}
C#對原型模式的支持
在C#里面,我們可以很容易的通過Clone()方法實現原型模式。任何類,只要想支持克隆,必須實現C#中的ICloneable接口。ICloneable接口中有一Clone方法,可以在類中復寫實現自定義的克隆方法??寺〉膶崿F方法有兩種:淺拷貝(shallow copy)與深拷貝(deep copy)。
淺拷貝與深拷貝
下面給出淺拷貝與深拷貝的兩個例子,例子使用了ICloneable接口。C#中的數組是引用型的變量,我們通過數組來進行演示:
淺拷貝:
using System;class ShallowCopy : ICloneable{ public int[] v = {1,2,3}; public Object Clone() { return this.MemberwiseClone(); } public void Display() { foreach(int i in v) Console.Write( i + ", "); Console.WriteLine(); }}class Client{ public static void Main() { ShallowCopy sc1 = new ShallowCopy(); ShallowCopy sc2 = (ShallowCopy)sc1.Clone(); sc1.v[0] = 9; sc1.Display(); sc2.Display(); }}
ShallowCopy對象實現了一個淺拷貝,因此當對sc1進行克隆時,其字段v并沒有克隆,這導致sc1與sc2的字段v都指向了同一個v,因此,當修改了sc1的v[0]后,sc2的v[0]也發生了變化。
深拷貝:
using System;class DeepCopy : ICloneable{ public int[] v = {1,2,3}; // 默認構造函數 public DeepCopy() { } // 供Clone方法調用的私有構造函數 private DeepCopy(int[] v) { this.v = (int[])v.Clone(); } public Object Clone() { // 構造一個新的DeepCopy對象,構造參數為 // 原有對象中使用的 v return new DeepCopy(this.v); } public void Display() { foreach(int i in v) Console.Write( i + ", "); Console.WriteLine(); }}class Client{ public static void Main() { DeepCopy dc1 = new DeepCopy(); DeepCopy dc2 = (DeepCopy)dc1.Clone(); dc1.v[0] = 9; dc1.Display(); dc2.Display(); }}
關于原型模式的討論
原型模式通過復制原型(原型)而獲得新對象創建的功能,這里原型本身就是"對象工廠"(因為能夠生產對象),實際上原型模式和 Builder 模式、AbstractFactory 模式都是通過一個類(對象實例)來專門負責對象的創建工作(工廠對象),它們之間的區別是: Builder 模式重在復雜對象的一步步創建(并不直接返回對象),AbstractFactory 模式重在產生多個相互依賴類的對象,而原型模式重在從自身復制自己創建新類。