加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

解析设计模式中的Prototype原型模式及在C++中的使用

发布时间:2020-12-16 05:36:41 所属栏目:百科 来源:网络整理
导读:原型模式的意图是用原型实例指定创建对象的种类,并且通过拷贝这些原型创建新的对象。 适用性 当要实例化的类是在运行时刻指定时,例如,通过动态装载;或者 为了避免创建一个与产品类层次平行的工厂类层次时;或者 当一个类的实例只能有几个不同状态组合中

原型模式的意图是用原型实例指定创建对象的种类,并且通过拷贝这些原型创建新的对象。

适用性 
当要实例化的类是在运行时刻指定时,例如,通过动态装载;或者
为了避免创建一个与产品类层次平行的工厂类层次时;或者
当一个类的实例只能有几个不同状态组合中的一种时。建立相应数目的原型并克隆它们可能比每次用合适的状态手工实例化该类更方便一些。

关于这个模式,突然想到了小时候看的《西游记》,齐天大圣孙悟空再发飙的时候可以通过自己头上的 3 根毛立马复制出来成千上万的孙悟空,对付小妖怪很管用(数量最重要)。

原型模式也正是提供了自我复制的功能,就是说新对象的创建可以通过已有对象进行创建。在 C++中拷贝构造函数(Copy Constructor)曾经是很对程序员的噩梦,浅层拷贝和深层拷贝的魔魇也是很多程序员在面试时候的快餐和系统崩溃时候的根源之一。

结构图:

201639115129023.jpg (558×202)

原型模式提供了一个通过已存在对象进行新对象创建的接口(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; 
} 

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读