本例以以下结构图为例:

命令抽象类(Command)

namespace CommandPattern.CLASS
{
    //命令类
    public abstract class Command
    {
        protected Barbecuer receiver;

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

        public abstract void RunCommand();
    }
}
View Code

具体的命令类(BakechickenWing)

namespace CommandPattern.CLASS
{
    class BakeChickenWing:Command
    {
        public BakeChickenWing(Barbecuer person)
            : base(person)
        { }
        public override void RunCommand()
        {
            receiver.BakeChickenWing();
        }
    }
}
View Code

具体的命令类(BakeMutton)

namespace CommandPattern.CLASS
{
    class BakeMuttonCommand:Command
    {
        public BakeMuttonCommand(Barbecuer person)
            : base(person)
        { }
        public override void RunCommand()
        {
            receiver.BakeMutton();
        }
    }
}
View Code

烤肉者(Barbecuer)

namespace CommandPattern.CLASS
{
    //烤肉者
    public class Barbecuer
    {
        public void BakeMutton()
        {
            Console.WriteLine("烤羊肉串!");
        }

        public void BakeChickenWing()
        {
            Console.WriteLine("烤鸡翅!");
        }
    }
}
View Code

服务员类(Waiter)

namespace CommandPattern.CLASS
{
    class Waiter
    {
        private IList<Command> orders = new List<Command>();

        //设置订单
        public void SetOrder(Command command)
        {
            orders.Add(command);
            Console.WriteLine("增加订单:" + command.ToString() + "时间:" + DateTime.Now.ToString());
        }
        public void CancelOrder(Command command)
        {
            orders.Remove(command);
            Console.WriteLine("取消订单:" + command.ToString() + "时间:" + DateTime.Now.ToString() );
        }
        //通知执行
        public void Notify()
        {
            //command.RunCommand();
            foreach (Command cmd in orders)
            {
                cmd.RunCommand();
            }
        }
    }
}
View Code

测试类(TestMain)

namespace CommandPattern
{
    class TestMain
    {
        static void Main(string[] args)
        {
            Barbecuer boy = new Barbecuer();
            Command bakeMuttonCommand = new BakeMuttonCommand(boy);
            Command bakeChickenWingCommand = new BakeChickenWing(boy);
            Waiter waiter = new Waiter();

            waiter.SetOrder(bakeMuttonCommand);
            waiter.SetOrder(bakeChickenWingCommand);
            waiter.CancelOrder(bakeMuttonCommand);
            waiter.Notify();
        }

    }
}
View Code

 

posted on 2013-08-19 19:13  zxd543  阅读(117)  评论(0编辑  收藏  举报