【原创】设计模式面对面之命令模式

命令模式

类图:

 

常用的实现方式:

 指令处理对象

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

 使用场景:

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

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

 

posted @ 2017-11-14 17:53  杜俊强  阅读(212)  评论(0编辑  收藏  举报