10.18
实验16:命令模式
本次实验属于模仿型实验,通过本次实验学生将掌握以下内容:
1、理解命令模式的动机,掌握该模式的结构;
2、能够利用命令模式解决实际问题。
[实验任务一]:多次撤销和重复的命令模式
某系统需要提供一个命令集合(注:可以使用链表,栈等集合对象实现),用于存储一系列命令对象,并通过该命令集合实现多次undo()和redo()操作,可以使用加法运算来模拟实现。
实验要求:
1. 提交类图;
2. 提交源代码;
from typing import List
# 抽象命令类
class Command:
def execute(self):
raise NotImplementedError
def undo(self):
raise NotImplementedError
# 具体命令类:加法命令
class AddCommand(Command):
def __init__(self, operand1, operand2):
self.operand1 = operand1
self.operand2 = operand2
self.result = None
def execute(self):
self.result = self.operand1 + self.operand2
print(f"执行加法运算:{self.operand1} + {self.operand2} = {self.result}")
def undo(self):
if self.result is not None:
self.operand1 -= self.operand2
self.result = None
print(f"撤销加法运算:{self.operand1} + {self.operand2} = {self.operand1}")
# 命令列表类
class CommandList:
def __init__(self):
self.commands = []
self.currentIndex = -1
def addCommand(self, command):
self.commands.append(command)
self.currentIndex += 1
def undo(self):
if self.currentIndex >= 0:
self.commands[self.currentIndex].undo()
self.currentIndex -= 1
def redo(self):
if self.currentIndex < len(self.commands) - 1:
self.currentIndex += 1
self.commands[self.currentIndex].execute()
if __name__ == "__main__":
command_list = CommandList()
add_command1 = AddCommand(5, 3)
command_list.addCommand(add_command1)
add_command1.execute()
add_command2 = AddCommand(2, 4)
command_list.addCommand(add_command2)
add_command2.execute()
command_list.undo()
command_list.redo()
3. 注意编程规范。
浙公网安备 33010602011771号