外国永久网站,网校 039 网站建设多少钱,旅游网站源码下载,网页传奇合击组合模式#xff0c;顾名思义#xff0c;通过组合关系定义类间的关联关系#xff0c;实现了将对象组合成树形结构#xff0c;最终实现类的复用。可能是由于设计模式看的多了#xff0c;初看组合模式的类图#xff0c;感觉和装饰者模式类图很相似#xff0c;都是使用继承…组合模式顾名思义通过组合关系定义类间的关联关系实现了将对象组合成树形结构最终实现类的复用。可能是由于设计模式看的多了初看组合模式的类图感觉和装饰者模式类图很相似都是使用继承和组合关系当然也只是结构相似而已。
#include iostream
#include vector
using namespace std;class Component {
public:virtual void Operation() { }virtual void Add(const Component com) { }virtual void Remove(const Component com) { }virtual Component* GetChild(int index) {return 0;}virtual ~Component() { }
};class Composite :public Component {
public:void Add(Component* com) {_coms.push_back(com);}void Operation() {for (auto com : _coms)com-Operation();}void Remove(Component* com) {//_coms.erase(com);}Component* GetChild(int index) {return _coms[index];}private:std::vectorComponent* _coms;
};class Leaf :public Component {
public:void Operation() {cout Leaf::Operation... endl;}
};int main() {Leaf *leaf new Leaf();leaf-Operation();Composite *com new Composite();com-Add(leaf);com-Operation();Component *leaf_ com-GetChild(0);leaf_-Operation();delete leaf;delete com;return 0;
}