场景:我去饭店吃饭,进去后对服务员说:“我要一个三明治”,服务员对厨师喊,“三明治一份”,我然后又说:“再来个煮鸡蛋。”服务员对厨师喊,“煮鸡蛋一份”,我说:“没了,就这些”,服务员喊,“就这些了,开做。”于是厨师开始做。

    //ICommand相当于服务员喊话的标准
    interface ICommand
    {
        void Execute();
    }

    //喊话内容:鸡蛋
    class CookEggCommand : ICommand
    {
        protected Receiver receiver;
   
        public CookEggCommand(Receiver receiver)
        {
            this.receiver = receiver;
        }

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

    //喊话内容:三明治
    class CookSandwichCommand : ICommand
    {
        protected Receiver receiver;

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

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

    //Receiver 相当于厨师
    class Receiver
    {
        //做鸡蛋
        public void CookEgg()
        {
            Console.WriteLine("Cooking an egg.");
        }
        //做三明治
        public void CookSandwich()
        {
            Console.WriteLine("Cooking a sandwich.");
        }
    }

    //Invoker 相当于服务员
    class Invoker
    {
        List<ICommand> commands = new List<ICommand>();

        //喊话
        public void SetCommand(ICommand command)
        {
            commands.Add(command);
        }

        //执行喊话内容
        public void ExecuteCommand()
        {
            foreach (ICommand command in commands)
            {
                command.Execute();
            }
            commands.Clear();
        }
    }


    class Program
    {
        static void Main()
        {
            Receiver receiver=new Receiver();
            ICommand egg= new CookEggCommand(receiver);
            ICommand sandwich = new CookSandwichCommand(receiver);
            Invoker invoker = new Invoker();

            //服务员喊话,三明治一份
            invoker.SetCommand(sandwich);
            //服务员喊话,鸡蛋一份
            invoker.SetCommand(egg);
            //服务员喊话,没有别的了,做吧。
            invoker.ExecuteCommand();
            System.Console.ReadKey();
        }
    }

相关文章:

  • 2021-05-01
  • 2022-12-23
  • 2021-11-19
  • 2022-01-06
  • 2021-10-09
  • 2021-10-25
  • 2021-09-20
  • 2021-09-08
猜你喜欢
  • 2021-11-18
  • 2021-09-08
  • 2021-06-28
  • 2022-12-23
  • 2021-11-04
  • 2021-07-19
  • 2021-11-20
相关资源
相似解决方案