Command Pattern

来源:互联网 发布:绝对值的算法 初一 编辑:程序博客网 时间:2024/05/20 08:27

动机:把一个请求封装为一个对象,使得不同的请求得到不同的响应;并且对请求进行排队,以及支持UnDo/Redo的操作。

1.Receiver:知道如何执行请求的对象

public class Receiver
    {
        public void Action()
        {
            Console.WriteLine("Called Receiver.Action()");
        }
    }

2.Command:操作执行的接口,包括Receiver的引用;

public abstract class Command
    {
        public abstract void Execute();
        protected Receiver _receiver;


        public Command(Receiver receiver)
        {
            _receiver = receiver;
        }
    }

3.ConcreteCommand

public class ConcereteCommand : Command
    {
        public ConcereteCommand(Receiver receiver)
            : base(receiver)
        {


        }
        
        public override void Execute()
        {
            _receiver.Action();
        }
    }

4.Invoke, 用户:告诉Comand执行请求;

public class Invoke
    {
        private Command _command;
        public void SetCommand(Command command)
        {
            _command = command;
        }


        public void ExecuteCommand()
        {
            _command.Execute();
        }
    }


5. 创建命令,设置它的接收者;

public class ClientCommand
    {
        public void F()
        {
            Receiver r = new Receiver();
            Command command = new ConcereteCommand(r);
            Invoke invoke = new Invoke();


            invoke.SetCommand(command);
            invoke.ExecuteCommand();


        }
    }

原创粉丝点击