原型模式C++实现
2018-02-11 14:54
357 查看
原型模式就是对本身进行克隆。克隆完成后,各自独立,互不影响。
原型类: #include "StdAfx.h"#include "Prototype.h"Prototype::Prototype(void) : m_age(0){}Prototype::~Prototype(void){}Prototype* Prototype::Clone(void){ return new Prototype(this);}Prototype::Prototype(Prototype* rhs){ if (NULL != rhs) { this->m_name = rhs->GetName(); this->m_age = rhs->GetAge(); }}void Prototype::SetName(string rhs){ this->m_name = rhs;}string Prototype::GetName(void){ return this->m_name;}void Prototype::SetAge(int rhs){ this->m_age = rhs;}int Prototype::GetAge(void){ return this->m_age;} 客户端: // MyPrototype.cpp : 定义控制台应用程序的入口点。//#include "stdafx.h"#include "Prototype.h"#include <iostream>using namespace std;int _tmain(int argc, _TCHAR* argv[]){ Prototype* a = new Prototype(); a->SetAge(10); a->SetName("Zhangsan"); Prototype* b = a->Clone(); cout<<"A Name:" <<a->GetName() <<endl; cout<<"A Age:" <<a->GetAge() <<endl; cout<<"B Name:" <<b->GetName() <<endl; cout<<"B Age:" <<b->GetAge() <<endl; delete a; a = NULL; b->SetName("WangWu"); b->SetAge(20); cout<<"B Name:" <<b->GetName() <<endl; cout<<"B Age:" <<b->GetAge() <<endl; return 0;} 运行结果:
原型类: #include "StdAfx.h"#include "Prototype.h"Prototype::Prototype(void) : m_age(0){}Prototype::~Prototype(void){}Prototype* Prototype::Clone(void){ return new Prototype(this);}Prototype::Prototype(Prototype* rhs){ if (NULL != rhs) { this->m_name = rhs->GetName(); this->m_age = rhs->GetAge(); }}void Prototype::SetName(string rhs){ this->m_name = rhs;}string Prototype::GetName(void){ return this->m_name;}void Prototype::SetAge(int rhs){ this->m_age = rhs;}int Prototype::GetAge(void){ return this->m_age;} 客户端: // MyPrototype.cpp : 定义控制台应用程序的入口点。//#include "stdafx.h"#include "Prototype.h"#include <iostream>using namespace std;int _tmain(int argc, _TCHAR* argv[]){ Prototype* a = new Prototype(); a->SetAge(10); a->SetName("Zhangsan"); Prototype* b = a->Clone(); cout<<"A Name:" <<a->GetName() <<endl; cout<<"A Age:" <<a->GetAge() <<endl; cout<<"B Name:" <<b->GetName() <<endl; cout<<"B Age:" <<b->GetAge() <<endl; delete a; a = NULL; b->SetName("WangWu"); b->SetAge(20); cout<<"B Name:" <<b->GetName() <<endl; cout<<"B Age:" <<b->GetAge() <<endl; return 0;} 运行结果:
相关文章推荐
- 设计模式C++实现(4)——原型模式、模板方法模式
- 原型模式及C++实现
- 设计模式C++实现(5)——原型模式、模板方法模式
- 设计模式---原型模式(C++实现)
- 设计模式之 原型模式(prototype)(C++实现 深拷贝 + 浅拷贝版本[bug])
- 设计模式C++实现(4)——原型模式(Prototype)
- 大话设计模式C++实现-第9章-原型模式
- 设计模式C++实现(5)——原型模式、模板方法模式
- 设计模式之原型模式(C++实现)
- 设计模式C++实现(5)——原型模式、模板方法模式
- 设计模式C++实现--原型模式、模板方法模式
- C++设计模式实现--原型模式
- 设计模式C++实现(5)——原型模式、模板方法模式
- 23种设计模式之原型模式(创建型,5 Prototype,c++实现)
- 设计模式C++实现(5)——原型模式、模板方法模式
- 原型模式及C++代码实现
- 设计模式C++实现(5)——原型模式、模板方法模式
- 设计模式C++实现(5)——原型模式、模板方法模式
- 设计模式之原型模式及c++实现
- 设计模式C++实现(5)——原型模式、模板方法模式