码迷,mamicode.com
首页 > 其他好文 > 详细

原型模式

时间:2015-05-28 00:12:00      阅读:204      评论:0      收藏:0      [点我收藏+]

标签:

1】什么是原型模式?

原型模式即复制,或者克隆模式。

【2】原型模式代码示例:

代码示例1:
#include <iostream>
#include <string>
using namespace std;

class Prototype
{
private:
    string str;
public:
    Prototype(string s)
    {
        str = s;
    }
    Prototype()
    {
        str = "";
    }
    void show()
    {
        cout << str << endl;
    }
    virtual Prototype *clone() = 0;
};

class ConcretePrototype1 : public Prototype
{
public:
    ConcretePrototype1(string s) : Prototype(s)
    {}
    ConcretePrototype1(){}
    virtual Prototype *clone()
    {
        ConcretePrototype1 *p = new ConcretePrototype1();
        *p = *this;
        return p;
    }
};


class ConcretePrototype2 : public Prototype
{
public:
    ConcretePrototype2(string s) : Prototype(s)
    {}
    ConcretePrototype2(){}
    virtual Prototype *clone()
    {
        ConcretePrototype2 *p = new ConcretePrototype2();
        *p = *this;
        return p;
    }
};

int main()
{
    ConcretePrototype1 *test = new ConcretePrototype1("小李");
    ConcretePrototype2 *test2 = (ConcretePrototype2 *)test->clone();
    test->show();
    test2->show();
    return 0;
}

代码示例2:

#include <iostream>
#include <string>
using namespace std;
 
class Resume
{
private:
    string name, sex, age, timeArea, company;
public:
    Resume(string s)
    {
        name = s;
    }
    void setPersonalInfo(string s, string a)
    {
        sex = s;
        age = a;
    }
    void setWorkExperience(string t, string c)
    {
        timeArea = t;
        company = c;
    }
    void display()
    {
        cout << name << "  " << sex << "  " << age << endl;
        cout << "工作经历:  " << timeArea << "  " << company << endl;

    }
    Resume *clone()
    {
        Resume *b = new Resume(name);
        b->setPersonalInfo(sex, age);
        b->setWorkExperience(timeArea, company);
        return b;
    }
};


int main()
{
    Resume *r = new Resume("李俊宏");      
    r->setPersonalInfo("","26");
    r->setWorkExperience("2007-2010","读研究生");
    r->display();
    

    Resume *r2 = r->clone();
    r2->setWorkExperience("2003-2007","读本科");
    
    r->display();
    r2->display();
    
    return 0;
}

 

原型模式

标签:

原文地址:http://www.cnblogs.com/leijiangtao/p/4534641.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!