使用命令模式设计一个图形绘制系统,该系统可以绘制矩形、椭圆、三角形等图形,恢复和撤销功能。绘制类图并编程实现。
时间: 2024-06-08 07:05:36 浏览: 5
以下是使用命令模式设计的图形绘制系统的类图:
![command_pattern_example](https://user-images.githubusercontent.com/18255629/133359750-c9c2e4a1-3d1c-4c60-9f0e-e7a4e103fe24.png)
其中,`Receiver` 表示图形绘制系统中的接收者,负责实际执行绘制操作。`Command` 是命令的抽象类,声明了执行命令和撤销命令的方法。`ConcreteCommand` 是具体的命令类,继承自 `Command` 类,实现了命令的具体逻辑,并与 `Receiver` 进行交互。`Invoker` 是命令调用者,负责接收命令并将命令传递给 `Receiver` 执行。`Client` 是客户端,负责创建和配置命令对象,并将命令对象传递给 `Invoker`。
下面是具体的代码实现:
```python
from abc import ABC, abstractmethod
class Receiver:
def draw_rectangle(self, x1, y1, x2, y2):
print(f"Drawing rectangle from ({x1},{y1}) to ({x2},{y2})")
def draw_ellipse(self, x1, y1, x2, y2):
print(f"Drawing ellipse from ({x1},{y1}) to ({x2},{y2})")
def draw_triangle(self, x1, y1, x2, y2, x3, y3):
print(f"Drawing triangle with vertices ({x1},{y1}), ({x2},{y2}), ({x3},{y3})")
class Command(ABC):
@abstractmethod
def execute(self):
pass
@abstractmethod
def undo(self):
pass
class DrawRectangleCommand(Command):
def __init__(self, receiver: Receiver, x1, y1, x2, y2):
self.receiver = receiver
self.x1, self.y1, self.x2, self.y2 = x1, y1, x2, y2
def execute(self):
self.receiver.draw_rectangle(self.x1, self.y1, self.x2, self.y2)
def undo(self):
pass # 不支持撤销操作
class DrawEllipseCommand(Command):
def __init__(self, receiver: Receiver, x1, y1, x2, y2):
self.receiver = receiver
self.x1, self.y1, self.x2, self.y2 = x1, y1, x2, y2
def execute(self):
self.receiver.draw_ellipse(self.x1, self.y1, self.x2, self.y2)
def undo(self):
pass # 不支持撤销操作
class DrawTriangleCommand(Command):
def __init__(self, receiver: Receiver, x1, y1, x2, y2, x3, y3):
self.receiver = receiver
self.x1, self.y1, self.x2, self.y2, self.x3, self.y3 = x1, y1, x2, y2, x3, y3
def execute(self):
self.receiver.draw_triangle(self.x1, self.y1, self.x2, self.y2, self.x3, self.y3)
def undo(self):
pass # 不支持撤销操作
class Invoker:
def __init__(self):
self.commands = []
def add_command(self, command: Command):
self.commands.append(command)
def execute_commands(self):
for command in self.commands:
command.execute()
if __name__ == '__main__':
receiver = Receiver()
invoker = Invoker()
# 创建具体命令对象并添加到调用者中
invoker.add_command(DrawRectangleCommand(receiver, 0, 0, 100, 100))
invoker.add_command(DrawEllipseCommand(receiver, 50, 50, 150, 200))
invoker.add_command(DrawTriangleCommand(receiver, 200, 200, 250, 250, 300, 200))
# 执行命令
invoker.execute_commands()
```
在上述代码中,我们定义了三个具体的绘制命令类 `DrawRectangleCommand`、`DrawEllipseCommand` 和 `DrawTriangleCommand`,它们分别对应矩形、椭圆和三角形的绘制操作。这些命令类都实现了 `Command` 接口,其中 `execute` 方法用于执行绘制操作,`undo` 方法暂时不实现。
我们还定义了一个 `Invoker` 类,它负责接收命令并调用 `execute` 方法执行命令。客户端可以通过创建具体的命令对象并将其添加到 `Invoker` 中来完成绘制操作。
需要注意的是,在这个简单的示例中,我们并没有实现撤销操作。如果需要支持撤销功能,我们可以在 `Command` 接口中添加 `redo` 方法,并在具体命令类中实现撤销和重做逻辑。此外,我们还可以使用栈来存储执行过的命令,从而实现撤销和重做操作。