设计模式读书笔记:Composite(组合)
2015-07-10 16:01:01
意图:
将对象组合成树形结构以表示“部分-整体”的层次结构。Composite使得用户对单个对象和组合对象的使用具有一致性。
结构图:来自 《23种设计模式 - 郗晓勇》
实现:https://github.com/panshiqu/patterns/tree/master/Composite
Component
#include <iostream>
namespace NS_COMPOSITE {
class Component {
public:
Component(std::string name) : _name(name) {}
virtual ~Component() {}
virtual void operation(void)
{
std::cout << _name << std::endl;
}
virtual void add(Component *component) {}
virtual void remove(Component *component) {}
private:
std::string _name;
};
} /* namespace NS_COMPOSITE */
Composite
#include "Component.h"
#include <list>
namespace NS_COMPOSITE {
class Composite : public Component
{
public:
Composite(std::string name) : Component(name) {}
virtual ~Composite() {}
virtual void operation(void)
{
Component::operation();
std::list<Component *>::iterator itr = _components.begin();
for (; itr != _components.end(); itr++)
{
(*itr)->operation();
}
}
virtual void add(Component *component)
{
_components.push_back(component);
}
virtual void remove(Component *component)
{
// do remove
}
private:
std::list<Component *> _components;
};
} /* namespace NS_COMPOSITE */
Leaf
#include "Component.h"
namespace NS_COMPOSITE {
class Leaf : public Component
{
public:
Leaf(std::string name) : Component(name) {}
virtual ~Leaf() {}
virtual void operation(void)
{
Component::operation();
}
};
} /* namespace NS_COMPOSITE */
main
#include "Composite/Composite.h"
#include "Composite/Leaf.h"
using namespace NS_COMPOSITE;
int main(void)
{
Composite c1("c1");
Leaf l1("l1");
Composite c2("c2");
c1.add(&l1);
c1.add(&c2);
Leaf l2("l2");
c2.add(&l2);
c1.operation();
}
附加: