1. 程式人生 > >設計模式之原型模式(C++)

設計模式之原型模式(C++)

設計模式之原型模式

原型模式是用原型例項指定建立兌現的種類,並且通過拷貝這些原型建立新的物件。原型模式說白了其實就是有一個把自己拷貝一下的方法。該模式很好理解,該模式獨特地方不是類與類之間的關係,更多的是從語義上理解,只是實現了一個介面而已。

其UML圖如下:

原型模式UML圖

示例程式碼如下:

// PrototypeModel.h檔案
#pragma once
#include <iostream>
#include <string>
// 原型類
class Prototype
{
public:
	virtual Prototype * Clone() = 0;
};
// 
class ConcretePrototype_0
: public Prototype { public: ConcretePrototype_0(std::string name) { m_strTypeName = name; } virtual Prototype * Clone() { ConcretePrototype_0 *p = new ConcretePrototype_0(m_strTypeName); *p = *this; return p; } void Show() { std::cout << m_strTypeName << std::endl; } private
: std::string m_strTypeName; }; class ConcretePrototype_1 : public Prototype { public: ConcretePrototype_1(std::string name) { m_strTypeName = name; } virtual Prototype * Clone() { ConcretePrototype_1 *p = new ConcretePrototype_1(m_strTypeName); *p = *this; return p; } void Show() {
std::cout << m_strTypeName << std::endl; } private: std::string m_strTypeName; };

測試程式碼如下:

#include <iostream>
#include "PrototypeModel.h"

int main()
{
	using namespace std;
	ConcretePrototype_0 * p1 = new ConcretePrototype_0("A");
	ConcretePrototype_1 * p2 = (ConcretePrototype_1 *)(p1->Clone());
	p1->Show();
	p2->Show();
	delete p1;
	delete p2;

	getchar();
	return 0;
}

測試結果如下圖:

在這裡插入圖片描述