设计模式---------------------原型模式
2015-06-25 12:42
543 查看
原型模式的优点:
从一个对象在创建另外一个可定制的对象,而无需知道创建的任何细节,并且能提高创建性能(copy技术)。
下面先来看原型模式的结构图:
具体代码如下:
// Strategy.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <iostream>
#include <vector>
#include <string>
using namespace std;
class Prototype{
private:
string m_strName;
public:
Prototype(string strName){
m_strName = strName;
}
Prototype(){ m_strName = ""; }
void show(){
cout << m_strName << endl;
}
virtual Prototype* Clone() = 0;
};
class ConcreatePrototype1 :public Prototype{
public:
ConcreatePrototype1(string strName) :Prototype(strName){}
ConcreatePrototype1(){}
virtual Prototype*Clone(){
ConcreatePrototype1*p = new ConcreatePrototype1();
*p = *this;
return p;
}
};
class ConcreatePrototype2 :public Prototype{
public:
ConcreatePrototype2(string strName) :Prototype(strName){}
ConcreatePrototype2(){}
virtual Prototype*Clone(){
ConcreatePrototype2*p = new ConcreatePrototype2();
*p = *this;
return p;
}
};
int main(){
ConcreatePrototype1 *test = new ConcreatePrototype1("小王");
ConcreatePrototype2*test2 = (ConcreatePrototype2*)test->Clone();
test->show();
test2->show();
getchar();
getchar();
return 0;
}
从一个对象在创建另外一个可定制的对象,而无需知道创建的任何细节,并且能提高创建性能(copy技术)。
下面先来看原型模式的结构图:
具体代码如下:
// Strategy.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <iostream>
#include <vector>
#include <string>
using namespace std;
class Prototype{
private:
string m_strName;
public:
Prototype(string strName){
m_strName = strName;
}
Prototype(){ m_strName = ""; }
void show(){
cout << m_strName << endl;
}
virtual Prototype* Clone() = 0;
};
class ConcreatePrototype1 :public Prototype{
public:
ConcreatePrototype1(string strName) :Prototype(strName){}
ConcreatePrototype1(){}
virtual Prototype*Clone(){
ConcreatePrototype1*p = new ConcreatePrototype1();
*p = *this;
return p;
}
};
class ConcreatePrototype2 :public Prototype{
public:
ConcreatePrototype2(string strName) :Prototype(strName){}
ConcreatePrototype2(){}
virtual Prototype*Clone(){
ConcreatePrototype2*p = new ConcreatePrototype2();
*p = *this;
return p;
}
};
int main(){
ConcreatePrototype1 *test = new ConcreatePrototype1("小王");
ConcreatePrototype2*test2 = (ConcreatePrototype2*)test->Clone();
test->show();
test2->show();
getchar();
getchar();
return 0;
}
相关文章推荐
- 使用C++实现JNI接口需要注意的事项
- PropertyChangeListener简单理解
- 关于指针的一些事情
- 什么是设计模式
- 设计模式之创建型模式 - 特别的变量问题
- 设计模式之创建型模式
- 浅谈设计模式的学习
- c++ primer 第五版 笔记前言
- share_ptr的几个注意点
- Lua教程(一):在C++中嵌入Lua脚本
- Lua教程(二):C++和Lua相互传递数据示例
- C++联合体转换成C#结构的实现方法
- C++编写简单的打靶游戏
- C++变位词问题分析
- C/C++数据对齐详细解析
- C++基于栈实现铁轨问题
- C++中引用的使用总结
- C++中调用Lua函数实例
- Lua和C++的通信流程代码实例
- C与C++之间相互调用实例方法讲解