动易学校网站管理系统 漏洞,新氧网站头图怎么做的,百度搜索推广开户,网站搜索 代码意图#xff1a;将对象组成树状结构以表示“部分#xff0d;整体”的层次结构#xff0c;使得Client对单个对象和组合对象的使用具有一致性。 上下文#xff1a;在树型结构的问题中#xff0c;Client必须以不同的方式处理单个对象和组合对象。能否提供一种封装#xff0c… 意图将对象组成树状结构以表示“部分整体”的层次结构使得Client对单个对象和组合对象的使用具有一致性。 上下文在树型结构的问题中Client必须以不同的方式处理单个对象和组合对象。能否提供一种封装统一简单元素和复杂元素的概念让对象容器自己来实现自身的复杂结构让Client可以像处理简单元素一样来处理复杂元素从而使Client与复杂元素的内部结构解耦 UML Component为Composite中的对象声明接口在适当情况下实现所有类公共接口的默认行为声明一个接口用于访问和管理Component的子部件在递归结构中定义一个接口用于访问一个父部件并在适当的情况下实现它。 Leaf在Composite中表示叶子对象。 Composite存储子部件并定义有子部件的那些部件的行为。 Client通过Component接口操作Composite的对象。 代码
#include iostream
#include list
using namespace std;class Component
{
public:string name;Component(string name):name(name){}virtual void add(Component *c) 0;virtual void remove(Component *c) 0;virtual void display(int depth) 0;
};class Leaf:public Component
{
public:// Component interfaceLeaf(string name):Component(name){}
public:void add(Component *c);void remove(Component *c);void display(int depth);
};void Leaf::add(Component *c )
{(void)(c);//消除警告cout 不能向叶子中添加Component endl;
}void Leaf::remove(Component *c)
{(void)(c);//Warningcout 不能从叶子中删除Component endl;
}void Leaf::display(int depth)
{cout string(depth,-) this-name endl;
}class Composite:public Component
{
public:listComponent* children;// Component interfaceComposite(string name):Component(name){}
public:void add(Component *c);void remove(Component *c);void display(int depth);
};
void Composite::add(Component *c)
{children.push_back(c);
}void Composite::remove(Component *c)
{children.remove(c);
}void Composite::display(int depth)
{cout string(depth,-) this-name endl;listComponent*::iterator it;for(it children.begin();it ! children.end();it){Component *c *it;c-display(depth 2);}
}
int main()
{Composite *root new Composite(树干);root-add(new Leaf(树叶1));root-add(new Leaf(树叶2));Composite *c1 new Composite(树枝1);c1-add(new Leaf(树叶1-1));c1-add(new Leaf(树叶1-2));root-add(c1);Composite *c1_1 new Composite(树枝1-1);c1_1-add(new Leaf(树叶1-1-1));c1_1-add(new Leaf(树叶1-1-2));c1-add(c1_1);root-add(new Leaf(树叶3));root-display(1);return 0;
}结果
-树干
---树叶1
---树叶2
---树枝1
-----树叶1-1
-----树叶1-2
-----树枝1-1
-------树叶1-1-1
-------树叶1-1-2
---树叶3