Created
October 16, 2019 04:19
-
-
Save simongarisch/bc7af1d09b059d0f8b86508996be4176 to your computer and use it in GitHub Desktop.
Python structural patterns - composite
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# The composite pattern describes a group of objects that is treated the | |
# same way as a single instance of the same type of object. | |
from abc import ABC, abstractmethod | |
class Shape(ABC): | |
@abstractmethod | |
def draw(self): | |
raise NotImplementedError | |
class Circle(Shape): | |
def draw(self): | |
print("Drawing a circle") | |
class Square(Shape): | |
def draw(self): | |
print("Drawing a square") | |
class Triangle(Shape): | |
def draw(self): | |
print("Drawing a triangle") | |
class Drawing(Shape): | |
def __init__(self): | |
self._shapes = [] | |
def add(self, shape): | |
self._shapes.append(shape) | |
def remove(self, shape): | |
self._shapes.remove(shape) | |
def draw(self): | |
for shape in self._shapes: | |
shape.draw() | |
drawing = Drawing() | |
for shape in [Circle(), Square(), Triangle()]: | |
drawing.add(shape) | |
drawing.draw() | |
# Drawing a circle | |
# Drawing a square | |
# Drawing a triangle |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment