"""
Composite pattern example.
"""
from abc import ABCMeta, abstractmethod
NOT_IMPLEMENTED = "You should implement this."
class Graphic:
__metaclass__ = ABCMeta
@abstractmethod
def print(self):
raise NotImplementedError(NOT_IMPLEMENTED)
class CompositeGraphic(Graphic):
def __init__(self):
self.graphics = []
def print(self):
for graphic in self.graphics:
graphic.print()
def add(self, graphic):
self.graphics.append(graphic)
def remove(self, graphic):
self.graphics.remove(graphic)
class Ellipse(Graphic):
def __init__(self, name):
self.name = name
def print(self):
print("Ellipse:", self.name)
ellipse1 = Ellipse("1")
ellipse2 = Ellipse("2")
ellipse3 = Ellipse("3")
ellipse4 = Ellipse("4")
graphic = CompositeGraphic()
graphic1 = CompositeGraphic()
graphic2 = CompositeGraphic()
graphic1.add(ellipse1)
graphic1.add(ellipse2)
graphic1.add(ellipse3)
graphic2.add(ellipse4)
graphic.add(graphic1)
graphic.add(graphic2)
graphic.print()
import java.util.ArrayList;
/** "Component" */
interface Graphic {
//Prints the graphic.
public void print();
}
/** "Composite" */
class CompositeGraphic implements Graphic {
//Collection of child graphics.
private final ArrayList<Graphic> childGraphics = new ArrayList<>();
//Adds the graphic to the composition.
public void add(Graphic graphic) {
childGraphics.add(graphic);
}
//Prints the graphic.
@Override
public void print() {
for (Graphic graphic : childGraphics) {
graphic.print(); //Delegation
}
}
}
/** "Leaf" */
class Ellipse implements Graphic {
//Prints the graphic.
@Override
public void print() {
System.out.println("Ellipse");
}
}
/** Client */
class CompositeDemo {
public static void main(String[] args) {
//Initialize four ellipses
Ellipse ellipse1 = new Ellipse();
Ellipse ellipse2 = new Ellipse();
Ellipse ellipse3 = new Ellipse();
Ellipse ellipse4 = new Ellipse();
//Creates two composites containing the ellipses
CompositeGraphic graphic2 = new CompositeGraphic();
graphic2.add(ellipse1);
graphic2.add(ellipse2);
graphic2.add(ellipse3);
CompositeGraphic graphic3 = new CompositeGraphic();
graphic3.add(ellipse4);
//Create another graphics that contains two graphics
CompositeGraphic graphic1 = new CompositeGraphic();
graphic1.add(graphic2);
graphic1.add(graphic3);
//Prints the complete graphic (Four times the string "Ellipse").
graphic1.print();
}
}