ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

设计模式-Composite(创建型模式) 用于 递归构建 树 状 的组合结构,与Decorator的区别是 Composite旨在通过构造子类而添加新操作,而Decorator直接添加新操作。

2019-12-21 17:55:58  阅读:197  来源: 互联网

标签:Leaf Composite void Component 添加 include com Decorator


以下代码来源: 设计模式精解-GoF 23种设计模式解析附C++实现源码

//Component.h

#pragma once

class Component
{
public:
    Component();
    virtual ~Component();
    virtual void Operation() = 0;
    virtual void Add(const Component&);
    virtual void Remove(const Component&);
    virtual Component* getChild(int);
protected:
private:

};

//Component.cpp

#include"Component.h"
Component::Component(){}
Component::~Component(){}
void Component::Add(const Component& com){}
void Component::Remove(const Component& com){}
Component* Component::getChild(int index)
{
    return 0;
}

//composite.h

#include"Component.h"
#include<vector>

class Composite :public Component
{
public:
    Composite();
    virtual ~Composite();
    void Add(Component* com); 
    void Remove(Component* com);
    void Operation();
    Component* Getchild(int index);
protected:
private:
    std::vector<Component*>comVec;
};

//Composite.cpp

#include"Component.h"
#include"composite.h"

const int null = 0;

Composite::Composite(){}
Composite::~Composite(){}

void Composite::Operation(){
    for (std::vector<Component*>::iterator comIter = comVec.begin(); comIter != comVec.end(); ++comIter)
    {
        (*comIter)->Operation();
    }
}
void Composite::Add(Component* com)
{
    comVec.push_back(com);
}
void Composite::Remove(Component* com)
{
    //comVec.erase(&com);//此处有问题,求解释!!!
}
Component* Composite::Getchild(int index)
{
    return comVec[index];
}

//Leaf.h

#include"Component.h"
class Leaf :public Component
{
public:
    Leaf();
    virtual ~Leaf();
    void Operation();
protected:
private:

};

//Leaf.cpp

#include"Leaf.h"
#include<iostream>
Leaf::Leaf(){
}
Leaf::~Leaf(){}
void Leaf::Operation(){
    std::cout << "Leaf Operation..." << std::endl;
}

//main.cpp

#include"Component.h"
#include"composite.h"
#include"Leaf.h"
#include<iostream>
#include<string>
int main(int args, char* argv)
{
    Leaf* I = new Leaf();
    I->Operation();
    Composite* com = new Composite();
    com->Add(I);
    com->Operation();
    Component* II = com->Getchild(0);
    getchar();
    return 0;
}

标签:Leaf,Composite,void,Component,添加,include,com,Decorator
来源: https://www.cnblogs.com/fourmi/p/12077657.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有