命令者模式-马士兵设计模式教程 .

//Command模式经常用来作为还原功能,也就是Ctrl+Z
public abstract class Command {
	public abstract void execute();
	//返回上一步
	public abstract void unDo();
}

public class ShopingCommand extends Command{
	@Override
	public void execute() {
		System.out.println("逛街");
	}

	@Override
	public void unDo() {
		System.out.println("不逛街,回家");
	}
	
}

public class HugCommand extends Command{

	@Override
	public void execute() {
		System.out.println("拥抱");
	}

	@Override
	public void unDo() {
		System.out.println("展开双臂");
	}

}


public class Boy {
	List<Command> commands=new ArrayList<Command>();
	private String name;
	
	public String getName() {
		return name;
	}
	
	public void setName(String name) {
		this.name = name;
	}
	public void addCommand(Command m){
		commands.add(m);
	}
	public void dosomething(){
	}
	public void executeCommand(){
		for(Command m : commands){
			m.execute();
		}
	}
}


public class MM {
	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	private String name;
	
	public void order(Boy body){
		Boy b=new Boy();
		Command com1=new ShopingCommand();
		Command com2=new HugCommand();
		b.addCommand(com1);
		b.addCommand(com2);
		b.executeCommand();
	}
}


<PRE class=java name="code">public class Test {
	public static void main(String[] args) {
		MM mm=new MM();
		mm.setName("美女");
		Boy boy=new Boy();
		boy.setName("屌丝");
		mm.order(boy);
	}
	/**
	 * 运行结果:
	 * 逛街
	 * 拥抱
	 */
}</PRE>
<PRE></PRE>

你可能感兴趣的:(java,设计模式,String,command,Class)