java 命令模式

命令模式是一种常用实用的设计模式,它主要是通过三者的结合(命令,增加命令,事件激发)在一起,充分显示了灵活性,好了,废话少说。看下面一个例子
首先是建立命令接口CommandInterface.java

package command;
/**
 * 命令接口
 * @author Administrator
 *
 */
public interface CommandInterface {

	public void excute();
}


实现命令的接口类

package command;
/**
 * 命令执行类
 * @author Administrator
 *
 */
public class inCommand implements CommandInterface{

	@Override
	public void excute() {
		// TODO Auto-generated method stub
		System.out.println("in command");
	}

}


增加事件的接口

package command;
/**
 * 增加命令的接口
 * @author Administrator
 *
 */
public interface AddCommandInterface {

	public void setCommand(CommandInterface comd);
	public CommandInterface getCommand();
	
}

//上面这可以增加些自己需要的功能

增加事件的实现类

package command;

public class InAddCommand implements AddCommandInterface{
	private CommandInterface comd=null;
	@Override
	public void setCommand(CommandInterface comd) {
		// TODO Auto-generated method stub
		this.comd=comd;
	}

	@Override
	public CommandInterface getCommand() {
		// TODO Auto-generated method stub
		return comd;
	}

}

事件激发接口
package command;
/**
 * 建立事件激发接口
 * @author Administrator
 *
 */
public interface ActionInterface {

	public void actionPerformed(AddCommandInterface comInter);
	
	
	
}
//要不要这个类看自己的需求来建立的

实现激发事件的类
package command;

public class ActionCommand implements ActionInterface {

	@Override
	public void actionPerformed(AddCommandInterface comInter) {
		// TODO Auto-generated method stub
		comInter.getCommand().excute();
	}

}


管理类

	package command;
/**
 * 对命令接口的实现
 * @author Administrator
 *
 */
public class Actualize {

	private AddCommandInterface addCommand=null;
	public Actualize() {
		// TODO Auto-generated constructor stub
	}
	/**
	 * 增加命令
	 */
	public void addCommandInter(AddCommandInterface addCommand){
		this.addCommand=addCommand;
	}
	/**
	 * 执行命令
	 */
	public void addAction(ActionInterface action){
		action.actionPerformed(this.addCommand);
	}
	
}





实现类,也可以说是统一管理类吧,很方便的
package command;

public class ExcuteCommand {
  	
	public static void exec(CommandInterface com){
		Actualize actu=new Actualize();
		InAddCommand inAdd=new InAddCommand();
		inAdd.setCommand(com);
		actu.addCommandInter(inAdd);
		actu.addAction(new ActionCommand());		
	}
}


好了,到我们写代码去测度的了

package command;

public class TestCommand {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		inCommand in=new inCommand();
		ExcuteCommand.exec(in);
	//	outCommand out=new outCommand();
	//	ExcuteCommand.exec(out);
	//	printCommand print=new printCommand();
	//	ExcuteCommand.exec(print);
	}

}

你可能感兴趣的:(java)