在开发中,我们经常可能要递归构建树状的组合结构,Composite 模式则提供了很好的解决方案。
//Component.h
#pragma once
#include <memory>
class Component
{
public:
Component();
virtual ~Component();
public:
virtual void Operation() = 0;
virtual void Add(std::shared_ptr<Component> );
virtual void Remove(std::shared_ptr<Component> );
virtual std::shared_ptr<Component> GetChild(int );
protected:
private:
};
//Component.cpp
#include "stdafx.h"
#include "Component.h"
Component::Component()
{
}
Component::~Component()
{
}
void Component::Add(std::shared_ptr<Component> com)
{
}
std::shared_ptr<Component> Component::GetChild(int index)
{
return 0;
}
void Component::Remove(std::shared_ptr<Component> com)
{
}
//Composite.h
#pragma once
#include "Component.h"
#include <vector>
#include <memory>
using namespace std;
class Composite:public Component
{
public:
Composite();
~Composite();
public:
void Operation();
void Add(std::shared_ptr<Component> com);
void Remove(std::shared_ptr<Component> com);
std::shared_ptr<Component> GetChild(int index);
protected:
private:
//vector<Component*> comVec;
vector<std::shared_ptr<Component>> comVec;
};
//Composite.cpp
#include "stdafx.h"
#include "Composite.h"
#include "Component.h"
#define NULL 0 //define NULL POINTOR
Composite::Composite()
{
//vector<Component*>::iterator itend = comVec.begin();
}
Composite::~Composite()
{
}
void Composite::Operation()
{
vector<std::shared_ptr<Component>>::iterator comIter = comVec.begin();
for (;comIter != comVec.end();comIter++)
{
(*comIter)->Operation();
}
}
void Composite::Add(std::shared_ptr<Component> com)
{
comVec.push_back(com);
}
void Composite::Remove(std::shared_ptr<Component> com)
{
//comVec.erase(&com);
//comVec.erase(com);
for(auto iter = comVec.begin();iter != comVec.end();)
{
if(*iter ==com )
comVec.erase(iter);
else
{
++iter;
}
}
}
std::shared_ptr<Component> Composite::GetChild(int index)
{
return comVec[index];
}
//Leaf.h
#pragma
#include "Component.h"
class Leaf:public Component
{
public:
Leaf();
~Leaf();
void Operation();
protected:
private:
};
//Leaf.cpp
#include "stdafx.h"
#include "Leaf.h"
#include <iostream>
using namespace std;
Leaf::Leaf()
{
}
Leaf::~Leaf()
{
}
void Leaf::Operation()
{
cout<<"Leaf operation....."<<endl;
}
int main(int argc, _TCHAR* argv[])
{
std::shared_ptr<Leaf> l(new Leaf());
l->Operation();
std::shared_ptr<Composite> com = std::make_shared<Composite>();
com->Add(l);
com->Operation();
//std::shared_ptr<Component> ll(com->GetChild(0));
std::shared_ptr<Component> ll = com->GetChild(0);
ll->Operation();
return 0;
}
Composite 模式在实现中有一个问题就是要提供对于子节点(Leaf)的管理策略,这里使用的是 STL 中的 vector,可以提供其他的实现方式,如数组、链表、Hash 表等。
Composite 模式通过和 Decorator 模式有着类似的结构图,但是 Composite 模式旨在构造类,而 Decorator 模式重在不生成子类即可给对象添加职责。Decorator 模式重在修饰,而Composite 模式重在表示。