C++原型设计模式小练习

#include <iostream>

using namespace std;

class ProtoType
{
public:
    ProtoType(){}
    virtual ~ProtoType(){}
    virtual ProtoType* Clone() = 0;
};

class ConcreteClass1 : public ProtoType
{
public:
    int     field1;
    int     field2;
public:
    ConcreteClass1()
        : field1(0)
        , field2(0)
    {

    }
    ConcreteClass1(const ConcreteClass1& rightvalue)
    {
        this->field1 = rightvalue.field1;
        this->field2 = rightvalue.field2;
    }
    virtual ConcreteClass1* Clone()
    {
        return new ConcreteClass1(*this);
    }
    friend void operator << (std::ostream& oss, const ConcreteClass1& rightvalue)
    {
        oss << &rightvalue;
    }
};



int main()
{
    ConcreteClass1 *object1 = new ConcreteClass1();
    object1->field1 = 1;
    object1->field2 = 2;
    cout << "The value of field1 in object1:" << object1->field1
         << ", field2:" << object1->field2 << endl;

    ConcreteClass1 *object2 = object1->Clone();
    cout << "The value of field1 in object2:" << object2->field1
         << ", field2:" << object2->field2 << endl;

    cout << "the address of object1:" << object1 << endl;
    cout << "the address of object2:" << object2 << endl;

    delete object1;
    delete object2;
    return 0;
}

 

posted @ 2013-03-19 10:03  特洛伊人  阅读(315)  评论(0编辑  收藏  举报