解析設計形式中的Prototype原型形式及在C++中的應用。本站提示廣大學習愛好者:(解析設計形式中的Prototype原型形式及在C++中的應用)文章只能為提供參考,不一定能成為您想要的結果。以下是解析設計形式中的Prototype原型形式及在C++中的應用正文
原型形式的意圖是用原型實例指定創立對象的品種,而且經由過程拷貝這些原型創立新的對象。
實用性
當要實例化的類是在運轉時辰指准時,例如,經由過程靜態裝載;或許
為了不創立一個與產物類條理平行的工場類條理時;或許
當一個類的實例只能有幾個分歧狀況組合中的一種時。樹立響應數量的原型並克隆它們能夠比每次用適合的狀況手工實例化該類更便利一些。
關於這個形式,忽然想到了小時刻看的《西紀行》,齊天年夜聖孫悟空再發飙的時刻可以經由過程本身頭上的 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;
}