Composite模式

Composite模式

 
一、遇到的问题:
    开发中,经常可能要递归构建树状的组合结构,Composite模式可助你。
二、意图:
    将对象组合成树形结构以表示"部分-整体"的层次结构,Composite使得用户对单个对象和组合对象的使用具有一致性。
三、C++代码示例:
 
//component.h
#ifndef COMPONENT_H
#define COMPONENT_H

class Component{

public:
    Component();
    virtual ~Component();
public:
    virtual void Operation() = 0;
    virtual void Add(const Component*);
    virtual void Remove(Component *com);
    virtual Component* GetChild(int);
};

#endif // COMPONENT_H

//component.cpp
#include "component.h"

Component::Component(){

}

Component::~Component(){

}

void Component::Add(const Component *){

}

void Component::Remove(Component *com){

}

Component* Component::GetChild(int index){

    return 0;
}

//composite.h
#ifndef COMPOSITE_H
#define COMPOSITE_H

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

class Composite{

public:
    Composite();
    ~Composite();
public:
    void Operation();
    void Add(Component* com);
    void Remove(Component *com);
    Component* GetChild(int index);
private:
    std::vector<Component*> comVec;
};

#endif // COMPOSITE_H

//composite.cpp
#include "composite.h"
#include "component.h"
#include <algorithm>

using std::vector;

Composite::Composite(){

}
Composite::~Composite(){

    if(!comVec.empty()){
        comVec.clear();
    }
}

void Composite::Operation(){

    vector<Component*>::iterator comIter = comVec.begin();
    for(;comIter != comVec.end();++comIter){
        (*comIter)->Operation();
    }
}

void Composite::Add(Component *com){

    comVec.push_back(com);
}

void Composite::Remove(Component *com){

    std::vector<Component*>::iterator pos;
    pos = find(comVec.begin(),comVec.end(),com);
    if(pos != comVec.end()){
        comVec.erase(pos);
    }
}

Component* Composite::GetChild(int index){

    return comVec[index];
}

//leaf.h
#ifndef LEAF_H
#define LEAF_H
#include "composite.h"
#include "component.h"

class Leaf : public Component{

public:
    Leaf();
    ~Leaf();
    void Operation();
};

#endif // LEAF_H

//leaf.cpp
#include "leaf.h"
#include <iostream>

using std::cout;
using std::endl;

Leaf::Leaf(){

}

Leaf::~Leaf(){

}

void Leaf::Operation(){

    cout << "Leaf Operation..." << endl;
}

//main.cpp
#include "component.h"
#include "composite.h"
#include "leaf.h"
#include <iostream>

int main(int argc,char* argv[]){

    Leaf *leaf = new Leaf();
    leaf->Operation();
    Composite* com = new Composite();
    com->Add(leaf);
    com->Operation();
    Component* dLeaf = com->GetChild(0);
    dLeaf->Operation();

    return 0;
}


 
 
四、总结:
    Composite模式和Decorator模式有类似的结构图,但Composite模式旨在构造类,而Decorator模式重在不生成子类
即可给对象添加方法。Decorator模式重在修饰,而Composite模式重在表示。
 

                
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值