这个例子用java写成,我现在发现,java与c#差别不很大
先写一个厨师类
public class Barbecuer {
public void BakeMutton()
{
System.out.println("烤羊肉串");
}
public void BakeChickenWing()
{
System.out.println("烤鸡翅!");
}
}
在写一个命令类
public abstract class Command {
protected Barbecuer receiver;
public Command(Barbecuer receiver)
{
this.receiver=receiver;
}
abstract public void ExecuteCommand();
}
写两个类继承command类
public class BakeMuttonCommand extends Command{
public BakeMuttonCommand(Barbecuer receiver) {
super(receiver);
// TODO Auto-generated constructor stub
}
@Override
public void ExecuteCommand() {
// TODO Auto-generated method stub
receiver.BakeMutton();
}
}
public class BakeChickenWingCommand extends Command{
public BakeChickenWingCommand(Barbecuer receiver) {
super(receiver);
// TODO Auto-generated constructor stub
}
@Override
public void ExecuteCommand() {
// TODO Auto-generated method stub
receiver.BakeChickenWing();
}
}
写服务员类
public class Waiter {
private Command command;
public void SetOrder(Command command)
{
this.command=command;
}
public void Notify()
{
command.ExecuteCommand();
}
}
写测试类
public class Program {
public static void main(String[] args) {
// TODO Auto-generated method stub
//开店前得准备
Barbecuer boy =new Barbecuer();
Command bakeMuttonCommand1 = new BakeMuttonCommand(boy);
Command bakeMuttonCommand2= new BakeMuttonCommand(boy);
Command bakeChickenWingCommand1 = new BakeChickenWingCommand(boy);
Waiter girl=new Waiter();
//开门营业
girl.SetOrder(bakeMuttonCommand1);
girl.Notify();
girl.SetOrder(bakeMuttonCommand2);
girl.Notify();
girl.SetOrder(bakeChickenWingCommand1);
girl.Notify();
}
}