composite模式
以基类为根节点,共三类
叶子节点类
其他..(非根 非叶子)
composite.h
#ifndef _COMPOSITE_H
#define _COMPOSITE_H
#include <vector>
#include <iostream>
using namespace std;
class Component{
public:
Component() {}
virtual ~Component() {}
public:
virtual void Operation()=0;
virtual void Add(const Component&) {}
virtual void Remove(const Component&) {}
virtual Component* GetChild(int) {}
};
class Composite : public Component
{
public: Composite() {};
~Composite() {}
public:
void Add(Component* com) { comVec.push_back(com); }
void Remove(Component *com)
{ vector::iterator comIter = comVec.begin(); for (; comIter != comVec.end(); comIter++) { if (*comIter == com) { comVec.erase(comIter); } } }
Component* GetChild(int index) { return comVec[index]; }
void Operation()
{ vector::iterator comIter = comVec.begin(); for (; comIter != comVec.end(); comIter++) { (*comIter)->Operation(); } }
private:
vectorcomVec;
};
class Leaf : public Component
{
public:
Leaf() {}
~Leaf() {}
void Operation() {
cout << "Leaf operation" << endl;
}
};
#endif // _COMPOSITE_H
composite.cpp
#include "composite.h"
int main()
{
Leaf* l = new Leaf;
l->Operation();
Composite* com = new Composite;
com->Add(l);
com->Operation();
Component* ll = com->GetChild(0);
ll->Operation();
return 0;
}
编译:make composite