zoukankan      html  css  js  c++  java
  • 【原创】设计模式面对面之命令模式

    命令模式

    类图:

     

    常用的实现方式:

     指令处理对象

    public interface IReceiver  {
    
            void Operation();
        }//end IReceiver
    View Code
    public class ReceiverA : IReceiver {
    
            public ReceiverA(){
    
            }
    
            public void Operation(){
                Console.WriteLine("由ReceiverA处理");
            }
    
        }//end ReceiverA
    View Code
    public class ReceiverB : IReceiver {
    
            public ReceiverB(){
    
            }
    
            public void Operation(){
                Console.WriteLine("由ReceiverB处理");
            }
    
        }//end ReceiverB
    View Code

    指令对象

    public interface ICommand  {
    
            void Execute();
        }//end ICommand
    View Code
    public class CommandRealizeA : ICommand {
    
            private readonly IReceiver _receiver;
    
            public CommandRealizeA(){
                _receiver=new ReceiverA();
            }
    
            public void Execute(){
                _receiver.Operation();
            }
    
        }//end CommandRealizeA
    View Code
    public class CommandRealizeB : ICommand {
    
            private readonly IReceiver _receiver;
    
            public CommandRealizeB()
            {
                _receiver=new ReceiverB();
            }
    
            public void Execute(){
                _receiver.Operation();
            }
    
        }//end CommandRealizeB
    View Code

    调用对象

    public class Invoker {
    
            private ICommand _command;
    
            public Invoker(){
                _command=new CommandRealizeA();//默认指令
            }
    
            public void Invoke()
            {
                _command.Execute();
            }
    
            /// 
            /// <param name="command"></param>
            public void SetCommand(ICommand command)
            {
                _command = command;
            }
    
        }//end Invoker
    View Code

     使用场景:

     当每次请求或者动作会出现一连串操作,此时可以考虑。比如提交表单后台涉及到数据库操作,日志操作,缓存操作等等,这些操作可以用命令模式去控制。

     命令模式将命令的调用者(发出者),执行者,处理着,从一个紧耦合的动作,分离开来,主要用来复杂的动作解耦和指令(命令)管理。

  • 相关阅读:
    selenium 手写xpath
    pythonselenium面试常问问题
    pytest介绍
    pytest + allure 生成自测报告
    python自动化接口面试题
    接口测试面试题汇总
    Eclipse 视图与视窗
    Access数据库密码为不可见字符的处理方式
    eclipse 导出jar 没有主清单属性的解决方法
    如何在 Windows 下编译 OpenSSL VS2013
  • 原文地址:https://www.cnblogs.com/dujq/p/7832927.html
Copyright © 2011-2022 走看看