先写一个厨师类
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();
}
}
再写服务生类
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
public class Waiter {
private List<Command> orders = new ArrayList<Command>();
public void SetOrder(Command command)
{
if(command.toString() == "鸡翅")
{
System.out.println("服务员:鸡翅没有了,请点别的烧烤。");
}
else
{
orders.add(command);
System.out.println("增加定点:"+command.toString());
}
}
public void CancelOrder(Command command)
{
orders.remove(command);
System.out.println("取消订单"+command.toString());
}
public void Notify()
{
for (Command command : orders) {
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.SetOrder(bakeMuttonCommand2);
girl.SetOrder(bakeChickenWingCommand1);
//点菜完毕,通知厨房
girl.Notify();
}
}