命令模式在SWING中经常用到,这种模式经常用在按钮上面。我现在把SWING中的这种模式提取出来供大家一起来讨论。
首先建立命令借口
public interface CommandInterface {
public void excute();
}
在建立两个不同的命令执行类
public class InCommand implements CommandInterface{
/**
* 具体的命令执行内容
*/
public void excute() {
System.out.println("int command");
}
}
public class OutCommand implements CommandInterface{
/**
* 具体的命令执行内容
*/
public void excute() {
System.out.println("out command");
}
}
建立增加命令的借口
public interface AddCommandInterface {
public void setCommand(CommandInterface comd);
public CommandInterface getCommand();
}
增加命令的实现类
public class OutAddCommand implements AddCommandInterface{
private CommandInterface comd = null;
/**
* 获得命令
*/
public CommandInterface getCommand() {
return this.comd;
}
/**
* 设置命令
*/
public void setCommand(CommandInterface comd) {
this.comd = comd;
}
}
建立事件激发借口
public interface ActionInterface {
public void actionPerformed(AddCommandInterface comInter);
}
事件激发借口的实现类
public class ActionCommand implements ActionInterface{
public void actionPerformed(AddCommandInterface comInter)
{
comInter.getCommand().excute();
}
}
对命令接口的实现
public class Actualize {
private AddCommandInterface addCommand = null;
public Actualize()
{
}
/**
* 增加命令
* @param addCommand
*/
public void addCommandInter(AddCommandInterface addCommand)
{
this.addCommand = addCommand;
}
/**
* 执行命令
* @param action
*/
public void addAction(ActionInterface action)
{
action.actionPerformed(this.addCommand);
}
}
封装接口的实现
public class ExcuteCommand {
public static void exec(CommandInterface com) {
Actualize actu = new Actualize();
OutAddCommand outAdd = new OutAddCommand();
outAdd.setCommand(com);
actu.addCommandInter(outAdd);
actu.addAction(new ActionCommand());
}
}
具体命令的调用
public class TestCommand {
public static void main(String[] args)
{
OutCommand out = new OutCommand();
ExcuteCommand.exec(out);
InCommand in = new InCommand();
ExcuteCommand.exec(in);
}
}
输出结果:
out command
int command