合成模式:将对象以树形结构组织起来,以达成“部分-整体” 的层次结构,使得客户端对单个对象和组合对象的使用具有一致性. 合成模式就是一个处理对象的树结构的模式。合成模式把部分与整体的关系用树结构表示出来。合成模式使得客户端把一个个单独的成分对象和由他们复合而成的合成对象同等看待。

//Component
class Component{
public:
Component(){}
virtual ~Component(){}
virtual void Operation() =0 ;
virtual void Add(const Component&){}
virtual void Remove(const Component&){}
virtual Component *GetChild(int){}
};
//Composite
class Composite:public Component{
public:
Composite(){}
~Composite(){}
void Operation(){
vector<Component *>:iterator comIter = comVec.begin();
for(;comIter != comVec.end();comIter++){
(*comIter) ->Operation();
}
}
void Add(Component *com){
comVec.push_back(coom);
}
void Remove(Component *com){
comVec.erase(&com);
}
Component *GetChild(int index){
return comVec[index];
}
private:
Vector<Component *> comVec;
};
class Leaf: public Component{}
public:
Leaf(){}
~Leaf(){}
void Operation(){ ... }
;
int main(void){
Leaf *l = new Leaf();
l->Operation();
Composite *com = new Composite();
com -> Add(1);
com ->Operation();
Component *ll = com->GetChild(0);
ll -> Operation();
return 0;
}
本文深入探讨了合成模式的概念及其在对象树结构中的应用,阐述了如何通过此模式实现单个对象与组合对象的一致性操作,为开发者提供了一种灵活且高效地管理对象层次结构的方法。
1486

被折叠的 条评论
为什么被折叠?



