python设计模式第二十四天【命令模式】

时间:2024-05-04 13:06:01

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