一.建立型模式 Prototype 模式
阿新 • • 發佈:2018-11-27
Prototype 提供了自我複製的功能
- Prototype 模式提供了一個通過已存在物件進行新物件建立的介面(Clone),Clone()實現和具體的實現語言相關,在 C++中我們將通過拷貝建構函式實現之。
#include"prototype.h" #include<iostream> using namespace std; int main() { prototype *p = new ConcretePrototype(); prototype *p1 = p->Clone(); system(main"pause"); return 0; }
#pragma once #include<iostream> using namespace std; class prototype { public: virtual ~prototype(); virtual prototype* Clone() const = 0; protected : prototype(); }; class ConcretePrototype:public prototype { public: ConcretePrototype();prototype.h~ConcretePrototype(); ConcretePrototype(const ConcretePrototype &cp); prototype* Clone() const; };
#include "prototype.h" prototype::prototype() { } prototype::~prototype() { } ConcretePrototype::ConcretePrototype() { } ConcretePrototype::~ConcretePrototype() { } ConcretePrototype::ConcretePrototype(prototype.cppconst ConcretePrototype & cp) { cout << "concretePrototype copy" << endl; } prototype * ConcretePrototype::Clone() const { return new ConcretePrototype(*this); }