组合模式:将对象组合成树型结构以表示‘部分-整体’的层次结构。组合模式使用户对单个对象和组合对象的使用具有一致性。
需求中体现部分和整体层次的结构时,已经你希望用户可以忽略组合对象与单个对象的不同,统一使用组合结构中的所有对象时,就应该考虑使用组合模式
-
class Component{
-
protected:
-
string name;
-
public:
-
virtual void add( Component c);
-
virtual void remove( Component c);
-
virtual void Display( int depth);
-
};
-
-
class Leaf : public Component{
-
public:
-
Leaf(string name):Component(name){}
-
void add(Component c){
-
cout<<\"Cannot add to a leaf\"<<endl;
-
}
-
void remove( Component c ){
-
cout<<\"Cannot remove from a leaf\"<<endl;
-
}
-
void Display( int depth )
-
{
-
cout<<new string(\'-\',depth)<<name<<endl;
-
}
-
};
-
-
class Composite : public Component{
-
private:
-
list<Component> children = new list<Component>();
-
public:
-
Composite(string name):Component(name) {}
-
void add(Component c){
-
children.add(c);
-
}
-
void remove( Component c ){
-
children.remove(c);
-
}
-
void Display( int depth )
-
{
-
cout<<new string(\'-\',depth)<<name<<endl;
-
for( Component component in children)
-
{
-
component.Display(depth+2);
-
}
-
}
-
};
-
-
void main()
-
{
-
Composite root=new Composite(\"root\");
-
root.add(new leaf(\"Leaf A\"));
-
root.add(new leaf(\"Leaf B\"));
-
-
Composite comp=new Composite(\"Composit X\");
-
comp.add(new leaf(\"Leaf XA\"));
-
comp.add(new leaf(\"Leaf XB\"));
-
-
root.add(comp);
-
-
Composite comp2=new Composite(\"Composit XY\");
-
comp.add(new leaf(\"Leaf XYA\"));
-
comp.add(new leaf(\"Leaf XYB\"));
-
-
comp.add(comp2);
-
-
root.add(new leaf(\"leaf C\"));
-
-
leaf lef=new leaf(\"new leaf D\");
-
root.add(lef);
-
root.remove(lef);
-
}
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/29012686/viewspace-1131033/
,如需转载,请注明出处,否则将追究法律责任。