.net 学习&研究

命令模式的一个示例

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

    //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();
        }
    }

posted on 2007-11-08 17:21  球球  阅读(218)  评论(0编辑  收藏  举报

导航