Skip to content
Snippets Groups Projects
Commit 940048a6 authored by Florian Burger's avatar Florian Burger
Browse files

added solution 4

parent 7966e963
No related branches found
No related tags found
No related merge requests found
import random
class ShapeFactory:
factories = {}
@staticmethod
def add_factory(shape_id, shape_factory):
assert issubclass(shape_factory, FactoryCreatable), "Not creatable!" # we test that this is the right type
ShapeFactory.factories[shape_id] = shape_factory.create # we know that it has a create
@staticmethod
def create_shape(id):
shape_id = id.__name__ # class name as id
if id not in ShapeFactory.factories.keys():
ShapeFactory.add_factory(shape_id, id) # we pass in the class again
return ShapeFactory.factories[shape_id]() # we can simply call it with ()
class Shape(object):
pass
class FactoryCreatable:
@classmethod
def create(cls):
return cls()
class Circle(Shape, FactoryCreatable):
def draw(self):
print("Circle.draw")
def erase(self):
print("Circle.erase")
class Square(Shape, FactoryCreatable):
def draw(self):
print("Square.draw")
def erase(self):
print("Square.erase")
class Triangle(Shape, FactoryCreatable):
def draw(self):
print("Triangle.draw")
def erase(self):
print("Triangle.erase")
# what follows is the client code, we want to randomly create shape type objects
def shape_name_gen(n):
types = Shape.__subclasses__()
for i in range(n):
yield random.choice(types) # NOTE: We now pass in the Shape sub-class itself
shapes = [ShapeFactory.create_shape(i)
for i in shape_name_gen(5)]
for shape in shapes:
shape.draw()
shape.erase()
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment