| class Shape: |
| @classmethod |
| def create_shape(cls, shape_type): |
| if shape_type == "circle": |
| return Circle() |
| elif shape_type == "square": |
| return Square() |
| else: |
| raise ValueError("Unknown shape type") |
| |
| class Circle(Shape): |
| def draw(self): |
| print("Drawing a circle") |
| |
| class Square(Shape): |
| def draw(self): |
| print("Drawing a square") |
| |
| # 利用工厂方法创建形状 |
| circle = Shape.create_shape("circle") |
| circle.draw() # 输出: Drawing a circle |
| |
| square = Shape.create_shape("square") |
| square.draw() # 输出: Drawing a square |
在这个例子中,Shape类有一个类方法create_shape,它根据传入的shape_type返回差别的形状实例。