zoukankan      html  css  js  c++  java
  • 原型模式 ProtoType

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

    用c++做此模式时,注意深拷贝与浅拷贝

    //原型设计模式
    #include <IOSTREAM>
    #include "string"
    using namespace std;
    class Prototype{        //基类提供clone接口
    public:
        virtual Prototype * clone()=0;
        virtual void show() = 0;
    };
    
    class Card:public Prototype{
    public:
        Card():age(20),name("Jack"){
        }
        Card(int mage,string mname):age(mage),name(mname){
        }
        Card(const Card & other){
            this->age = other.age;
            this->name = other.name;
        }
        Prototype * clone();
    
        void show(){
            cout<<"name : "<<name<<" age : "<<age<<endl;
        }
    private:
        int age;
        string name;
    };
    Prototype * Card::clone(){
        return new Card(*this);
    }
    int main(int argc, char* argv[])
    {
        Prototype * card = new Card;
        card->show();
        Prototype * cardcopy = card->clone();
        cardcopy->show();
        delete card;
        delete cardcopy;
    
        Prototype * card2 = new Card(100,"Mike");
        card2->show();
        Prototype * card2copy = card2->clone();
        card2copy->show();
        delete card2;
        delete card2copy;
        return 0;
    }

    提供一个ProtoType基类以提供clone和show接口,有原型拷贝功能的类继承ProtoType类。

  • 相关阅读:
    新加坡
    android alt + /
    豌豆荚开源技术
    有意思的
    android view
    localstorage性能
    Android WebView使用基础
    关于hash
    Android 近百个项目的源代码,覆盖Android开发的每个领域
    10个经典的Android开源项目(附源码包)
  • 原文地址:https://www.cnblogs.com/xiumukediao/p/4625332.html
Copyright © 2011-2022 走看看