写一个简单工厂模式的代码demo
时间: 2023-06-03 16:07:52 浏览: 57
好的,这是一个简单工厂模式的代码示例:
```
class Shape:
def draw(self):
pass
class Rectangle(Shape):
def draw(self):
print("Drawing a rectangle")
class Circle(Shape):
def draw(self):
print("Drawing a circle")
class ShapeFactory:
@staticmethod
def get_shape(shape_type):
if shape_type == "Rectangle":
return Rectangle()
elif shape_type == "Circle":
return Circle()
else:
return None
if __name__ == "__main__":
shape_factory = ShapeFactory()
shape = shape_factory.get_shape("Rectangle")
shape.draw()
shape = shape_factory.get_shape("Circle")
shape.draw()
```
这个示例中,我们定义了 `Shape` 类,它是一个抽象类,并定义了一个 `draw` 方法。然后我们定义了两个子类:`Rectangle` 和 `Circle`,它们分别继承了 `Shape` 类,并重写了 `draw` 方法。最后,我们定义了一个工厂类 `ShapeFactory`,它有一个静态方法 `get_shape`,根据给定的参数创建不同的形状对象。