命令模式(Command)

作者:追风剑情 发布于: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()
        {

        }
    }
}


标签: 设计模式

Powered by emlog  蜀ICP备18021003号-1   sitemap

川公网安备 51019002001593号