c++组合模式和原型模式一起使用
来源:互联网 发布:unity3d 删除project 编辑:程序博客网 时间:2024/04/29 15:23
#include "stdafx.h"#include <iostream>#include <vector>using namespace std;class Component{public:virtual Component* clone() = 0;virtual void operation() = 0;virtual void Add(Component* pComponent) {}virtual void Remove(Component* pComponent) {}virtual Component* Getchild(int index) const {return 0;}virtual ~Component() {}};class Composite:public Component{public:Composite() {m_vector.clear();}Composite(const Composite& rhs);Component* clone();void Add(Component* pComponent);void Remove(Component* pComponent);Component* Getchild(int index) const;void operation();vector<Component*> GetData() const;private:vector<Component* > m_vector;};Component* Composite::clone(){return new Composite(*this);}Composite::Composite(const Composite& rhs){int nSize = rhs.GetData().size();m_vector.resize(nSize);//m_vector = rhs.GetData();//int a = 5;vector<Component*> vt = rhs.GetData();memcpy(&m_vector[0], &vt[0], nSize*sizeof(Component*));}vector<Component*> Composite::GetData() const{return m_vector;}void Composite::Add(Component* pComponent){m_vector.push_back(pComponent);}void Composite::Remove(Component* pComponent){vector<Component* >::iterator it = m_vector.begin();while(it != m_vector.end()){if(*it == pComponent){it = m_vector.erase(it);}else{++it;}}}Component* Composite::Getchild(int index) const{if(index >0 && index <= (int)m_vector.size()){return m_vector[index];}}void Composite::operation(){cout<<"this is the composite"<<endl;vector<Component*>::iterator it = m_vector.begin();while (it != m_vector.end()){(*it)->operation();++it;}}class Leaf:public Component{public:Leaf() {}Leaf(const Leaf& rhs) {}Component* clone() {return new Leaf(*this);}void operation() {cout<<"this is the leaf"<<endl;}};int _tmain(int argc, _TCHAR* argv[]){Component* pRoot = new Composite();Leaf* pLeafA = new Leaf();Leaf* pLeafB = new Leaf();pRoot->Add(pLeafA);pRoot->Add(pLeafB);cout<<"before the delete:"<<endl;pRoot->operation();Component* pRootOld = pRoot->clone();pRoot->Remove(pLeafA);cout<<endl<<"after remove a leaf:"<<endl;pRoot->operation();cout<<endl<<"the state before delete:"<<endl;pRootOld->operation();getchar();return 0;}
0 0
- c++组合模式和原型模式一起使用
- 组合使用构造模式和原型模式创建对象
- js 组合使用原型模式和构造函数模式
- 6.2.4组合使用构造函数模式和原型模式
- 组合使用构造函数模式和原型模式。。
- 组合使用构造函数模式和原型模式
- 创建对象-组合使用构造函数和原型模式
- JavaScript学习-组合使用构造函数和原型模式
- javascript设计模式介绍(四)组合使用构造函数模式和原型模式
- js中组合使用构造函数模式和原型模式创建对象
- JavaScript面向对象 组合使用构造函数模式和原型模式
- JavaScript面向对象 组合使用构造函数模式和原型模式
- 在JS中组合使用构造函数模式和原型模式创建对象
- javascript中组合使用构造函数模式和原型模式创建对象
- JS创建对象之组合使用构造函数模式和原型模式
- JavaScript——组合使用构造函数模式和原型模式
- JavaScript 创建对象--组合使用构造函数模式和原型模式
- 对象的创建方法之三---组合使用构造函数模式和原型模式(最常用的模式)
- 获取安卓中的资源文件并按行读取
- php 基于PDO的预处理
- Spring整合JMS(一)——基于ActiveMQ实现
- 假设Oracle Linux官方yum源
- 剑指offer—连续子数组的最大和
- c++组合模式和原型模式一起使用
- j=j++的问题
- [BZOJ1640]=[BZOJ1692][Usaco2007 Dec]队列变换
- HTTPS和SSL/TLS协议
- finally执行顺序问题
- MySQL数据库学习笔记-锁机制
- ocp-81
- uvaoj 11384Help is needed for Dexter
- ocp-82