# -*- coding:UTF-8 -*-
import abc
class Component(metaclass=abc.ABCMeta):
def __init__(self, name):
self._name = name
@abc.abstractmethod
def add_component(self, c):
pass
@abc.abstractmethod
def remove_component(self, c):
pass
@abc.abstractmethod
def display(self, depth):
pass
class Leaf(Component):
def add_component(self, c):
print("Can't add to a leaf")
def remove_component(self, c):
print("Can't remove from a leaf")
def display(self, depth):
print('-' * depth + self._name)
class Composite(Component):
def __init__(self, name):
super().__init__(name)
self.children = []
def add_component(self, c):
self.children.append(c)
def remove_component(self, c):
self.children.remove(c)
def display(self, depth):
print('-' * depth + self._name)
for component in self.children:
component.display(depth + 2)
if __name__=='__main__':
root=Composite("root")
root.add_component(Leaf("leaf A"))
root.add_component(Leaf("leaf B"))
comp = Composite("Composite X")
comp.add_component(Leaf("leaf XA"))
comp.add_component(Leaf("leaf XB"))
root.add_component(comp)
comp2 = Composite('Composite XY')
comp2.add_component(Leaf("leaf XYA"))
comp2.add_component(Leaf("leaf XYB"))
comp.add_component(comp2)
root.add_component(Leaf('leaf C'))
leaf=Leaf("leaf D")
root.add_component(leaf)
root.remove_component(leaf)
root.display(1)