设计模式---命令模式

 

package com.ibeifemg.ex4;

public abstract class Command {
	private Peddler peddler;
	
	
	public Command(Peddler peddler) {
		this.peddler = peddler;
	}
	
	public Peddler getPeddler() {
		return peddler;
	}

	public void setPeddler(Peddler peddler) {
		this.peddler = peddler;
	}

	public abstract void sail();
}
package com.ibeifemg.ex4;

public class AppleCommand extends Command {

	public AppleCommand(Peddler peddler) {
		super(peddler);
	}

	public void sail() {
		this.getPeddler().sailApple();
	}
	
}
package com.ibeifemg.ex4;

public class BananaCommand extends Command{

	public BananaCommand(Peddler peddler) {
		super(peddler);
	}

	public void sail() {
		this.getPeddler().sailBanana();
	}

}
package com.ibeifemg.ex4;

/*
 * 小商贩
 */
public class Peddler {
	
	//卖苹果
	public void sailApple() {
		System.out.println("卖苹果");
	}
	
	//卖香蕉
	public void sailBanana() {
		System.out.println("卖香蕉");
	}
	
}

 原先是这样的

public class Waiter {
	private Command command;

	public Command getCommand() {
		return command;
	}

	public void setCommand(Command command) {
		this.command = command;
	}

	public void sail() {
		command.sail();
	}
}

现在 

package com.ibeifemg.ex4;

import java.util.ArrayList;
import java.util.List;

public class Waiter {
	private List<Command> commands = new ArrayList<Command>();


	public void setOrder(Command command) {
		commands.add(command);
	}

	public void removeOrder(Command command) {
		commands.remove(command);
	}
	
	public void sail() {
		for(Command command : commands) {
			command.sail();
		}
	}
}