Factory Pattern
# Interface
from abc import ABC, abstractmethod
class Shape(ABC):
@abstractmethod
def draw(self):
pass
# Class implementing the Shape Interface
class Circle(Shape):
def draw(self):
print("Drawing Circle")
# Class implementing the Shape Interface
class Square(Shape):
def draw(self):
print("Drawing Square")
# Factory Class
class ShapeFactory:
# Method that takes the type of shape as input
# and returns the corresponding object
def get_shape(self, shape_type):
if shape_type.lower() == "circle":
return Circle()
elif shape_type.lower() == "square":
return Square()
return None
# Driver code
if __name__ == "__main__":
# Object of ShapeFactory is initialized
shape_factory = ShapeFactory()
# Get a Circle object and call its draw method
shape1 = shape_factory.get_shape("CIRCLE")
if shape1: shape1.draw()
# Get a Square object and call its draw method
shape2 = shape_factory.get_shape("SQUARE")
if shape2: shape2.draw()
Last updated
