Composite - shoonie/StudyingDesignPattern GitHub Wiki
Compose objects into tree structure to represent part-whole hierarchies.Composite lets clients treat individual objects and compositions of object uniformly.
The Composite pattern
- defines class hierarchies consisting of primitive objects and composite objects.
- makes clients simple.
- make it easier to add new kinds of components.
- can make your design overly general.
- Explicit parent references.
- Sharing components.
- Maximizing the Component interface.
- Declaring the child management operations.
- Should Component implement a list of Components?
- Child ordering.
- Caching to improve performance.
- Who should delete components?
- What's the best data structure for storing components?
#include<iostream>
#include<vector>
using namespace std;
class node
{
int val;
public:
node(int x) :val(x) {}
int value()const
{
return val;
}
};
class IComposite
{
public:
virtual void Display(void)const = 0;
virtual void Add(node* elem) {}
};
class Single : public IComposite
{
node* elem;
public:
Single(node* x) :elem(x) {}
void Display(void)const
{
cout << elem->value() << "\n";
}
void Add(node* elem)
{
cout << "Not implemented\n";
}
~Single()
{
delete elem;
}
};
class Composite : public IComposite
{
vector<node*> elems;
public:
void Display(void)const
{
for (auto iter : elems)
{
cout << iter->value() << "\n";
}
cout << "\n";
}
void Add(node* elem)
{
elems.push_back(elem);
}
~Composite()
{
for (auto iter : elems)
{
delete iter;
}
}
};
int main()
{
node* a = new node(5);
node* b = new node(6);
node* c = new node(7);
IComposite* clientSingle = new Single(a); //leaf
clientSingle->Display();
clientSingle->Add(b); // can't add on the leaf
cout << "\n";
IComposite* clientComposite = new Composite();
clientComposite->Add(b);
clientComposite->Display();
clientComposite->Add(c);
clientComposite->Display();
return 1;
}