码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2018-08-12 21:49:36      阅读:134      评论:0      收藏:0      [点我收藏+]

标签:pyc   day   div   nump   ESS   meta   init   return   dao   

 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设计模式第二十四天【命令模式】

标签:pyc   day   div   nump   ESS   meta   init   return   dao   

原文地址:https://www.cnblogs.com/liuzhiqaingxyz/p/9464053.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!