您的位置:首页 > 编程语言 > C语言/C++

原型模式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;} 运行结果:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: