設計モードのPrototype(c++)

2031 ワード

Prototypeモデル:
機能:
プロトタイプインスタンスを使用して、作成するオブジェクトの種類を指定し、これらのプロトタイプをコピーして新しいオブジェクト、クローンオブジェクトを作成します.
Prototypeモデルクラス図は次のとおりです.
イメージ説明:お客様が鍵(ConcretePrototype)を配りたい場合は、鍵を持って鍵を配っている店に行くことができます.お店の主人は鍵の原型によって、鍵を配ってくれます.
具体的な簡単な実例実装:
/*Prototype.hxx*/

#ifndef _PROTOTYPE_H_
#define _PROTOTYPE_H_

class Prototype
{
public:
        virtual ~Prototype();
        virtual Prototype* Clone() const = 0;
protected:
        Prototype();
};

class ConcretePrototype:public Prototype
{
public:
        ConcretePrototype();
        ConcretePrototype(const ConcretePrototype& cp);
        ~ConcretePrototype();
        Prototype* Clone() const;
};
#endif //~_PROTOTYPE_H_
/*Prototype.cxx*/

#include "Prototype.hxx"
#include <iostream>

using namespace std;

Prototype::Prototype()
{

}

Prototype::~Prototype()
{

}

Prototype* Prototype::Clone() const 
{
	return 0;
}

//concretePrototype

ConcretePrototype::ConcretePrototype()
{

}

ConcretePrototype::~ConcretePrototype()
{

}

ConcretePrototype::ConcretePrototype(const ConcretePrototype& cp)
{
	cout<< "ConcretePrototype copy..." << endl;
}

Prototype* ConcretePrototype::Clone() const
{
	return new ConcretePrototype(*this);
}
/*main.cxx*/

#include "Prototype.hxx"

#include <iostream>
using namespace std;

int main(int argc, char* argv[])
{
	Prototype* p = new ConcretePrototype();
	Prototype* p1 = p->Clone();

	cout << p <<"||" << p1 << endl;
	
	delete p;
	p = NULL;
	if (p1)
	{
		delete p1;
		p1 = NULL;
	}
	return 0;
}

実行結果:
liujl@liujl-ThinkPad-Edge-E431:~/mysource/Design_model/Prototype$ g++ -o main main.o Prototype.o
liujl@liujl-ThinkPad-Edge-E431:~/mysource/Design_model/Prototype$ ./main 
ConcretePrototype copy...
0xf11010||0xf11030

参照ドキュメント:
1、c++設計モード.pdf
2、よくある設計モードの解析と実現(C++)の四-Prototypeモード