原型模式的意圖是用原型實例指定創建對象的種類,并且通過拷貝這些原型創建新的對象。
適用性
當要實例化的類是在運行時刻指定時,例如,通過動態裝載;或者
為了避免創建一個與產品類層次平行的工廠類層次時;或者
當一個類的實例只能有幾個不同狀態組合中的一種時。建立相應數目的原型并克隆它們可能比每次用合適的狀態手工實例化該類更方便一些。
關于這個模式,突然想到了小時候看的《西游記》,齊天大圣孫悟空再發飆的時候可以通過自己頭上的 3 根毛立馬復制出來成千上萬的孫悟空,對付小妖怪很管用(數量最重要)。
原型模式也正是提供了自我復制的功能,就是說新對象的創建可以通過已有對象進行創建。在 C++中拷貝構造函數(Copy Constructor)曾經是很對程序員的噩夢,淺層拷貝和深層拷貝的魔魘也是很多程序員在面試時候的快餐和系統崩潰時候的根源之一。
結構圖:
原型模式提供了一個通過已存在對象進行新對象創建的接口(Clone),Clone()實現和具體的實現語言相關,在 C++中我們將通過拷貝構造函數實現之。
例子
注意事項:
(1)根據原型模式的UML圖可以知道,實現要依賴于抽象要不要依賴與具體
(2)拷貝構造函數是核心,而且針對c++要進行的是深拷貝
(3)克隆函數的關鍵就是調用拷貝構造函數
#include <iostream> using namespace std; class Student { protected: int id; char name[10]; public: Student() { } ~Student() { cout<<"Desconstuct...."<<endl; } virtual Student *Clone() {} virtual void Show() { } }; class StudentTypeA:public Student { public: StudentTypeA(const char *name_input) { strcpy(name, name_input); this->id = 0; cout<<"Construction....."<<endl; } StudentTypeA(const StudentTypeA&other) { cout<<"Copy Construction..."<<endl; this->id = other.id; this->id ++; strcpy(this->name, other.name); } virtual StudentTypeA *Clone() { StudentTypeA *tmp = new StudentTypeA(*this); return tmp; } void Show() { cout<<"Student id == "<< id << " name == "<< name <<endl; } ~StudentTypeA() { cout<<"Deconstruction StudentTypeA"<<endl; } }; int main() { Student *student1 = new StudentTypeA("fulima"); Student *student2 = student1->Clone(); Student *student3 = student2->Clone(); student1->Show(); student2->Show(); student3->Show(); return 0; }