zoukankan      html  css  js  c++  java
  • 命令模式

    命令模式

     

    模式说明

    将请求封装成对象,从而使可用不同的请求对客户进行参数化;对请求排队或记录请求日志,以及支持可撤消的操作。

    模式结构图

    程序示例

    说明:调用者是遥控器,接受者是电视

    代码:

    复制代码
    class TV(object):
        def open(self):
            print 'turn on tv'
        def close(self):
            print 'turn off tv'
        def changeChannel(self):
            print 'change channel'
    
    class Command(object):
        _tv = TV()
        def __init__(self,tv):
            self._tv = tv
        def execute(self):
            pass
    
    class TurnOnCommand(Command):
        def execute(self):
            self._tv.open()
    
    class TurnOffCommand(Command):
        def execute(self):
            self._tv.close()
    
    class ChangeChannelCommand(Command):
        def execute(self):
            self._tv.changeChannel()
    
    class Controller(object):
        #_turnon = None
        #_turnoff = None
        #_changechannel = None
        def __init__(self,turnon,turnoff,changechannel):
            self._changechannel = changechannel
            self._turnon = turnon
            self._turnoff = turnoff
    
        def open(self):
            self._turnon.execute()
        def close(self):
            self._turnoff.execute()
        def changechannel(self):
            self._changechannel.execute()
    
    
    if '__main__' == __name__:
        tv = TV()
        turnon = TurnOnCommand(tv)
        turnoff = TurnOffCommand(tv)
        changechannel = ChangeChannelCommand(tv)
    
        controller = Controller(turnon,turnoff,changechannel)
        controller.open()
        controller.changechannel()
        controller.close()
    复制代码

    运行结果:

    参考来源:

    http://www.cnblogs.com/chenssy/p/3679190.html

    http://www.cnblogs.com/wuyuegb2312/archive/2013/04/09/3008320.html

    http://www.cnblogs.com/Terrylee/archive/2006/07/17/334911.html

  • 相关阅读:
    C++中类模板的概念和意义
    C++中模板类声明和实现能否分离?
    C/C++ 关于大小端模式,大小端字节序转换程序
    C++中的赋值操作符重载和拷贝构造函数
    C++中的友元
    C/C++内存对齐详解
    C++ 虚函数表、函数地址、内存布局解析
    虚析构函数的必要性(C++)
    C++中的抽象类和接口
    C++中的单例类模板
  • 原文地址:https://www.cnblogs.com/Siny0/p/11155825.html
Copyright © 2011-2022 走看看