设计模式:命令模式

命令模式(Command):将一个请求封装为一个对象,从而使你可用不同的请求对客户经行参数化,对请求排队或记录请求日志,以及支持可撤销的操作。

namespace CommandDesign
{
    public abstract class Command
    {
        protected Receiver receiver;
        public Command(Receiver receiver)
        {
            this.receiver = receiver;
        }
        public abstract void Execute();
    }
    public class ConcreteCommand : Command
    {
        public ConcreteCommand(Receiver receiver) : base(receiver) { }
        public override void Execute()
        {
            receiver.Action();
        }
    }
    public class Invoker
    {
        private Command command;
        public void SetCommand(Command command)
        {
            this.command = command;
        }
        public void ExecuteCommand()
        {
            command.Execute();
        }
    }
    public class Receiver
    {
        public void Action()
        {
            Console.WriteLine("执行请求!");
        }
    }
}
View Code

测试代码:

            Receiver r = new Receiver();
            Command c = new ConcreteCommand(r);
            Invoker i = new Invoker();
            i.SetCommand(c);
            i.ExecuteCommand();
View Code

 

posted @ 2016-03-17 10:16  uptothesky  阅读(156)  评论(0编辑  收藏  举报