原博主地址:(https://blog.csdn.net/LoveLion/article/details/17517213)
命令模式(Command Pattern):将一个请求封装为一个对象,从而让我们可用不同的请求对客户进行参数化;对请求排队或者记录请求日志,以及支持可撤销的操作。命令模式是一种对象行为型模式,其别名为动作(Action)模式或事务(Transaction)模式。
窗口类
class FBSettingWindow:
functionButtons = []
def addFunctionButton(self,fb):
self.functionButtons.append(fb)
def removeFunctionButton(self,fb):
self.functionButtons.remove(fb);
def display(self):
print("窗口名:"+self.name)
print("功能键有:")
for fb in self.functionButtons:
print(fb.name)
按键类,请求发送者
class FunctionButton:
def __init__(self,name):
self.name = name;
def onClick(self):
print(self.name+"功能键被点击")
self.command.execute()
命令类:先抽象后实现
from abc import ABCMeta, abstractmethod
class Command(metaclass=ABCMeta):
@abstractmethod
def execute(self):
pass
class HelpCommand(Command):
def execute(self):
self.hhObj.display()
class MinimizeCommand(Command):
def execute(self):
self.whObj.minimize()
实际处理类
class WindowHanlder:
def minimize(self):
print("将窗口最小化至托盘!")
class HelpHandler:
def display(self):
print("显示帮助文档!")
测试类
from 命令模式.FBSettingWindow import FBSettingWindow
from 命令模式.FunctionButton import FunctionButton
from 命令模式.Command import HelpCommand
from 命令模式.Hanlder import HelpHandler
from 命令模式.Hanlder import WindowHanlder
from 命令模式.Command import MinimizeCommand
fbsw = FBSettingWindow()#创建窗口
fbsw.name = "测试窗口"
fb1 = FunctionButton("功能键1")#新建按钮
fb2 = FunctionButton("功能键2")
command1 = HelpCommand()#具体命令
command2 = MinimizeCommand()
command1.hhObj = HelpHandler()#命令的实现
command2.whObj = WindowHanlder()
fb1.command = command1#命令绑定到按钮
fb2.command = command2
fbsw.addFunctionButton(fb1)#按钮绑定到窗口
fbsw.addFunctionButton(fb2)
fbsw.display()
fb1.onClick()#按钮命令
fb2.onClick()
测试结果
窗口名:测试窗口
功能键有:
功能键1
功能键2
功能键1功能键被点击
显示帮助文档!
功能键2功能键被点击
将窗口最小化至托盘!