原型模式C++实现

最近自学了设计模式,发现好多书的java实现的。因为本人是从事C++开发的,因此想尝试用C++自己实现一遍,加深理解。

原型模式

定义:用原型实例指定创建对象的种类,并且通过拷贝这些原型创建新的对象。

适用性:

1、  当一个系统应该独立于它的产品创建、构成和表示时,要使用原型模式

2、  当要实例化的类是在运行时刻指定时

3、  为了避免创建一个与产品类层次平行的工厂类层次时

4、  当一个类的实例只能有几个不同状态组合中的一种时

 

通用类结构:

 

 

实现:

class Prototype

{

public:

       Prototype(){}

       virtual~Prototype(){}

       virtualPrototype *Clone() = 0;

};

 

class ConcretePrototype1:public Prototype

{

public:

       ConcretePrototype1();

       ~ConcretePrototype1();

        ConcretePrototype1(constConcretePrototype1&);

        Prototype* Clone() ;

};

 

ConcretePrototype1::ConcretePrototype1()

{

        cout<<"ConcretePrototype1"<<endl;

}


ConcretePrototype1::ConcretePrototype1(const ConcretePrototype1& )

{

       cout<<"ConcretePrototype1copy"<<endl;

}

 

ConcretePrototype1::~ConcretePrototype1()

{

       cout<<"~ConcretePrototype1"<<endl;

}

 

Prototype*ConcretePrototype1::Clone()

{

       cout<<"CloneConcretePrototype1"<<endl;

       return new ConcretePrototype1(*this);

}

 

class ConcretePrototype2:public Prototype

{

public:

       ConcretePrototype2();

       ~ConcretePrototype2();

       ConcretePrototype2(const ConcretePrototype2&);

       Prototype* Clone() ;

};

 

ConcretePrototype2::ConcretePrototype2()

{

       cout<<"ConcretePrototype2"<<endl;

}

 

ConcretePrototype2::ConcretePrototype2(const ConcretePrototype2& )

{

       cout<<"ConcretePrototype2copy"<<endl;

}

 

ConcretePrototype2::~ConcretePrototype2()

{

       cout<<"~ConcretePrototype2"<<endl;

}

 

Prototype*ConcretePrototype2::Clone()

{

       cout<<"CloneConcretePrototype2"<<endl;

       return new ConcretePrototype2(*this);

}

 

Prototype*p1 = new ConcretePrototype1;

       Prototype *p3 = p1->Clone();

       Prototype *p2 = newConcretePrototype2;

       Prototype *p4 = p2->Clone();

 

实现需要注意的问题:

1、深拷贝和浅拷贝,最好是实现深拷贝

2、初始化克隆对象

 

 

                     

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值