Documentos de Académico
Documentos de Profesional
Documentos de Cultura
Código en C++[editar]
#include <iostream>
#include <vector>
class Component
{
protected:
string name;
public:
Component();
Component(string n);
virtual void add(Component*) {}
virtual void remove(Component*) {}
virtual void show(short) {}
};
Component::Component() {}
Component::Component(string n) : name(n) {}
Composite::Composite(string n) { name = n; }
void Composite::add(Component* component)
{
list.push_back(component);
}
void Composite::remove(Component* component)
{
list.erase(std::remove(list.begin(), list.end(), component),
list.end());
}
void Composite::show(short depth)
{
cout << name << " nivel: " << depth << endl;
for(vector<Component*>::const_iterator iter = list.begin(); iter
!= list.end(); ++iter)
{
if(*iter != 0)
{
(*iter)->show(depth + 1);
}
}
}
Leaf::Leaf(string n) { name = n; }
void Leaf::show(short depth)
{
cout << '-' << name << " (" << depth << ')' << endl;
}
int main()
{
Composite* root = new Composite("raiz");
root->add(new Leaf("hoja A"));
root->add(new Leaf("hoja B"));
root->add(comp);
root->add(new Leaf("hoja C"));
Leaf* h = new Leaf("hoja D");
root->add(h);
root->remove(h);
root->show(1);
delete h;
delete comp;
delete root;
return 0;
}
Código en Java[editar]
import java.util.*;
namespace WikipediaCompositePattern
{
public class Program
{
static void Main(string[] args)
{
Compuesto raiz = new Compuesto("root");
raiz.Agregar(new Hoja("hoja A"));
raiz.Agregar(new Hoja("hoja B"));
Compuesto comp = new Compuesto("compuesto X");
comp.Agregar(new Hoja("hoja XA"));
comp.Agregar(new Hoja("hoja XB"));
raiz.Agregar(comp);
raiz.Agregar(new Hoja("hoja C"));
Hoja l = new Hoja("hoja D");
raiz.Agregar(l);
raiz.Eliminar(l);
raiz.Mostrar(1);
}
}