Composite - shoonie/StudyingDesignPattern GitHub Wiki

Intent

Compose objects into tree structure to represent part-whole hierarchies.Composite lets clients treat individual objects and compositions of object uniformly.

Diagram

disgram

Consequences

The Composite pattern

  1. defines class hierarchies consisting of primitive objects and composite objects.
  2. makes clients simple.
  3. make it easier to add new kinds of components.
  4. can make your design overly general.

Implementation

  1. Explicit parent references.
  2. Sharing components.
  3. Maximizing the Component interface.
  4. Declaring the child management operations.
  5. Should Component implement a list of Components?
  6. Child ordering.
  7. Caching to improve performance.
  8. Who should delete components?
  9. What's the best data structure for storing components?

Sample Code

#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;
}
⚠️ **GitHub.com Fallback** ⚠️