python设计模式第二十四天命令模式
Posted liuzhiqaingxyz
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python设计模式第二十四天命令模式相关的知识,希望对你有一定的参考价值。
1.使用场景
(1)调用过程比较繁琐,需要封装
(2)调用参数需要进行处理封装
(3)需要添加额外的功能,例如,日志,缓存,操作记录等
2.代码实现
#!/usr/bin/env python #! _*_ coding:UTF-8 _*_ from abc import ABCMeta, abstractmethod class Receiver(object): ‘‘‘这时基本的类‘‘‘ def __init__(self): pass def action_one(self): print "action one..." def action_two(self): print "action two..." class Command(object): ‘‘‘这时命令抽象类‘‘‘ def __init__(self, receiver): self.receiver = receiver @abstractmethod def execute(self): pass class OneCommand(Command): def execute(self): self.receiver.action_one() class TwoCommand(Command): def execute(self): self.receiver.action_two() class Invoker(object): ‘‘‘这时最终调用目标‘‘‘ def __init__(self): pass def createCommand(self, command): self.command = command return self.command if __name__ == "__main__": receiver = Receiver() oneCommand = OneCommand(receiver) twoCommand = TwoCommand(receiver) invoker = Invoker() invoker.createCommand(oneCommand).execute() invoker.createCommand(twoCommand).execute()
结果:
/Users/liudaoqiang/PycharmProjects/numpy/venv/bin/python /Users/liudaoqiang/Project/python_project/day24_command/command_test.py
action one...
action two...
Process finished with exit code 0
以上是关于python设计模式第二十四天命令模式的主要内容,如果未能解决你的问题,请参考以下文章