Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1810379
  • 博文数量: 496
  • 博客积分: 12043
  • 博客等级: 上将
  • 技术积分: 4778
  • 用 户 组: 普通用户
  • 注册时间: 2010-11-27 14:26
文章分类

全部博文(496)

文章存档

2014年(8)

2013年(4)

2012年(181)

2011年(303)

2010年(3)

分类: C/C++

2012-06-05 10:51:02

原型模式优点:
    从一个对象再创建另外一个可定制的对象,而无需知道任何创建的细节。并能提高创建的性能。 说白了就 COPY 技术,把一个对象完整的 COPY 出一份。

下面是代码:
#include
#include
#include

using namespace std;

//抽象类
class ProtoType
{
private:
    string m_strName;
public:
    ProtoType(string strName)
    {
         m_strName = strName;
    }
    ProtoType(){m_strName = "";}
    virtual void Show()
    {
         cout << m_strName << endl;
    }
    virtual ProtoType* Clone() = 0;
};

//要克隆的之类ConcretePrototype1
class ConcretePrototype1 : public ProtoType
{
public:
    ConcretePrototype1(string strName) : ProtoType(strName){}
    ConcretePrototype1(){}
   
    virtual ProtoType* Clone()
    {
        ConcretePrototype1* p = new ConcretePrototype1();
        *p = *this;  //复制对象
   
        return p;
    }
};

//要克隆的之类ConcretePrototype2
class ConcretePrototype2 : public ProtoType
{
public:
    ConcretePrototype2(string strName) : ProtoType(strName){}
    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;
}


阅读(1165) | 评论(1) | 转发(0) |
给主人留下些什么吧!~~

zhou1742312012-06-05 20:01:31

小任哥牛B呀。。都上首页了