原型模式的C++實現
原型模式: 根據已有原型構造新物件
實現思路: 利用複製建構函式克隆自身
#include <iostream>
using namespace std;
class Prototype {
public:
Prototype() = default;
Prototype(const Prototype&);
Prototype* clone();
~Prototype();
void show();
private:
int m_data1;
int m_data2;
};
int main() {
Prototype p1;
auto np = p1.clone();
p1.show();
np->show();
delete np;
}
Prototype::Prototype(const Prototype& p)
:m_data1{p.m_data1},
m_data2{p.m_data2}
{
std::cout << "複製成功\n";
}
Prototype* Prototype::clone() {
return new Prototype(*this);
}
Prototype::~Prototype() {
std::cout << "prototype is died \n";
}
void Prototype::show() {
std::cout << "m_data1: " << m_data1
<< "m_data2: " << m_data2
<< std::endl;
}