命令模式

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

public class test : MonoBehaviour
{

    // Use this for initialization
    void Awake()
    {
        Receiver r = new Receiver();
        Command c = new ConcreteCommand(r);
        Invoker i = new Invoker();

        i.SetCommand(c);
        i.ExecuteCommand();
    }

}

class Receiver
{
    public void Action()
    {
        Debug.Log("执行请求!");
    }
}

abstract class Command
{
    protected Receiver receiver;

    public Command(Receiver receiver)
    {
        this.receiver = receiver;
    }

    abstract public void Execute();
}

//将一个接收者对象绑定于一个动作,调用接收者相应的操作,以实现Execute。
class ConcreteCommand : Command
{
    public ConcreteCommand(Receiver receiver) : base(receiver)
    {
    }

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

class Invoker
{
    private Command command;

    public void SetCommand(Command command)
    {
        this.command = command;
    }

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

你可能感兴趣的:(命令模式)