设计模式一日一练:原型模式(Prototype)

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

    我觉得原型模式比较适用于初始化比较复杂,而且新的实例与既有实例比较接近的情况。比如,钥匙有很多属性,比如类型、型号、大小、材质等,完全新制造一把钥匙需要初始化所有这些属性,而如果我们已经有一把了,需要再配两把,那么用原型模式可以省掉繁多的初始化工作。

// 钥匙型号  钥匙型号的编码,扁/十字/圆等
enum EKeyModel {
    M01,
    M02,
    M03
}

// 钥匙 prototype
class Key {
public:
    Key(EKeyModel m, int sz);
    Key(const Key& other);
    virtual ~Key();
    virtual Key* Clone() = 0;
    
    inline void SetModel(EKeyModel m) { this->model = m; }
    inline void SetSize(int sz) { this->size = sz; }
private:
    EKeyModel model;
    int size;
}

Key::Key(const Key& other) {
    this->model = other.model;
    this->size = other.size;
}


// 普通钥匙
class NormalKey: public Key {
public:
    NormalKey(EKeyModel m, int sz);
    NormalKey(const NormalKey& other);
    virtual ~NormalKey();
    virtual NormalKey* Clone();
}

NormalKey::NormalKey(EKeyModel m, int sz) : Key(m, sz) {
}

NormalKey::NormalKey(const NormalKey& other): Key(other) {
}

NormalKey* NormalKey::Clone() {
    return new NormalKey(*this);
}

// todo ...
// 电子钥匙 class ElectronicKey: public Key
// 智能钥匙 class SmartKey: public Key

// test
void Test() {
    Key* normalKey1 = new NormalKey(EKeyModel.M01, 10);
    Key* normalKey2 = normalKey1.Clone();
    Key* normalKey3 = normalKey1.Clone();
    normalKey3.SetSize(12);
    
    // todo ...  destroy
}
 

    PS. 我的设计模式系列blog,《设计模式》专栏,通过简单的示例演示设计模式,对于初学者很容易理解入门。深入学习请看GoF的《设计模式》。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值