使用简单工厂模式设计一个可以创建不同几何形状(Shape)
时间: 2024-06-12 10:10:41 浏览: 193
好的,我来为您解答。简单工厂模式是一种创建型设计模式,它提供了一种创建对象的最佳方式。在简单工厂模式中,我们创建一个工厂类,该类负责创建其他类的对象,而不是在代码中直接实例化它们。下面是一个可以创建不同几何形状的简单工厂类的示例代码:
```python
class ShapeFactory:
def create_shape(self, shape_type):
if shape_type == 'circle':
return Circle()
elif shape_type == 'rectangle':
return Rectangle()
elif shape_type == 'triangle':
return Triangle()
else:
raise ValueError('Invalid shape type')
```
在上面的代码中,我们定义了一个 ShapeFactory 类,它有一个 create_shape 方法,该方法接受一个字符串参数 shape_type,根据这个参数来创建不同的几何形状对象。如果传入的 shape_type 不是 'circle'、'rectangle' 或 'triangle' 中的任何一个,那么就会抛出一个 ValueError 异常。
下面是三个几何形状类的示例代码:
```python
class Circle:
def draw(self):
print('Drawing a circle')
class Rectangle:
def draw(self):
print('Drawing a rectangle')
class Triangle:
def draw(self):
print('Drawing a triangle')
```
这些类都有一个 draw 方法,用于绘制相应的几何形状。
现在我们可以使用 ShapeFactory 类来创建不同的几何形状对象了:
```python
factory = ShapeFactory()
circle = factory.create_shape('circle')
circle.draw() # 输出:Drawing a circle
rectangle = factory.create_shape('rectangle')
rectangle.draw() # 输出:Drawing a rectangle
triangle = factory.create_shape('triangle')
triangle.draw() # 输出:Drawing a triangle
```
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044901.png)
![-](https://img-home.csdnimg.cn/images/20241231044937.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![docx](https://img-home.csdnimg.cn/images/20241231044901.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)