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);
}

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值