鸟语天空
命令模式(Command)
post by:追风剑情 2016-6-17 18:05

应用场景:将行为请求者与行为执行者解耦。


using System;
using System.Collections.Generic;
using System.Text;

namespace CommandTest
{
    class Program
    {
        static void Main(string[] args)
        {
            //实际开发中,还可以把各命令加入队列中,并支持撤销(Undo)操作和恢复(Redo)操作。

            Receiver receiver = new Receiver();
            ICommand cmd1 = new Command1(receiver);
            ICommand cmd2 = new Command2(receiver);

            cmd1.Execute();
            cmd2.Execute();

            Console.Read();
        }
    }

    public interface ICommand
    {
        void Execute();
    }

    public class Command1 : ICommand
    {
        private Receiver receiver;

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

        public void Execute()
        {
            receiver.Show1();
        }
    }

    public class Command2 : ICommand
    {
        private Receiver receiver;

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

        public void Execute()
        {
            receiver.Show2();
        }
    }

    //命令接收者
    public class Receiver
    {
        public void Show1()
        {

        }

        public void Show2()
        {

        }
    }
}


评论:
发表评论:
昵称

邮件地址 (选填)

个人主页 (选填)

内容