酷代码 AI
菜单
服务商
DeepSeek字节豆包讯飞星火
更多选项

图形库重构:用简单工厂与工厂方法模式解决客户类使用难题

以下是使用简单工厂模式和工厂方法模式对上述系统进行重构的示例代码: ```python # 图形类的父类 class Shape: def set_color(self, color): pass def fill(self, fill_color): pass def set_size(self, size): pass def display(self): pass # 圆形类 class Circle(Shape): def __init__(self): print("创建圆形") def set_color(self, color): print(f"设置圆形边框颜色为: {color}") def fill(self, fill_color): print(f"填充圆形颜色为: {fill_color}") def set_size(self, size): print(f"设置圆形大小为: {size}") def display(self): print("显示圆形") # 三角形类 class Triangle(Shape): def __init__(self): print("创建三角形") def set_color(self, color): print(f"设置三角形边框颜色为: {color}") def fill(self, fill_color): print(f"填充三角形颜色为: {fill_color}") def set_size(self, size): print(f"设置三角形大小为: {size}") def display(self): print("显示三角形") # 简单工厂类 class ShapeFactory: def create_shape(self, shape_type): if shape_type == "circle": return Circle() elif shape_type == "triangle": return Triangle() else: raise ValueError("无效的图形类型") # 客户端类 class Client: def __init__(self, factory): self.factory = factory self.shape = None def create_shape(self, shape_type): self.shape = self.factory.create_shape(shape_type) def operate_shape(self): self.shape.set_color("red") self.shape.fill("blue") self.shape.set_size(10) self.shape.display() # 测试代码 factory = ShapeFactory() client = Client(factory) client.create_shape("circle") client.operate_shape() client.create_shape("triangle") client.operate_shape() ``` 在上述代码中: - 定义了一个抽象的`Shape`类,`Circle`和`Triangle`类继承自它。 - `ShapeFactory`类是简单工厂,根据传入的图形类型创建具体的图形对象。 - `Client`类不再直接创建图形对象,而是通过`ShapeFactory`来创建,并对图形进行操作。 这样就满足了隔离图形创建和使用的需求,并且符合开闭原则,方便更换图形或添加新图形,客户端无需修改太多代码。 ######[AI写代码神器 | 615点数解答 | 2024-10-10 16:21:39]

相关提问
本站限时免费提问中
实用工具查看更多
Linux在线手册 [开发类]
Jquery在线手册 [开发类]
今日油价 [生活类]
图片互转base64 [开发类]
时间转换器 [开发类]