原型模式

定义:

  从一个对象在创建另外一个可定制的对象,而且不需知道任何创建的细节。

  和重写拷贝构造函数一样,能简单的clong一个对象。注意深浅拷贝。

结构图:

  

 

 

 

 

 

 代码:

//抽象原型类,定义clong接口

class Prototype

{

public:

  Prototype Clong();

}

//具体原型类

class ConcretePrototype : Prototype

{

 //这个直接=就可以

    int IMyInt;
   //这个需要strncopy,不然浅拷贝
    char cMyChar[10]; 

public:

  Prototype Clong()

  {

    ConcretePrototype* CConcretePrototype = new ConcretePrototype();

    CConcretePrototype.IMyInt = this.IMyInt;

    strncpy(CConcretePrototype.cMyChar,this.cMyChar,10);

    return CConcretePrototype;

  ]

]

//客户端代码:

ConcretePrototype* CConcretePrototypeA = new ConcretePrototype();

CConcretePrototypeA.IMyInt = 7;

string strName = "hasake";

strncpy(CConcretePrototypeA.cMyChar,strName,strlen(strName));

 ConcretePrototype* CConcretePrototypeB = CConcretePrototypeA.Clong();

 

优点:能封装“某些结构复杂的对象"的创建工作;

缺点:需要注意深浅拷贝问题

posted @ 2020-07-25 14:31  吉尔加斯  阅读(101)  评论(0编辑  收藏  举报