JAVA设计模式- Command (命令)

命令模式有以下角色来组成            
1)  命令角色(Command):声明执行操作的接口。有java接口或者抽象类来实现。
2)  具体命令角色(Concrete Command):将一个接收者对象绑定于一个动作;调用接收者相应的操作,以实现命令角色声明的执行操作的接口。
3)  客户角色(Client):创建一个具体命令对象(并可以设定它的接收者)。
4)  请求者角色(Invoker):调用命令对象执行这个请求。
5)  接收者角色(Receiver):知道如何实施与执行一个请求相关的操作。任何类都可能作为一个接收者。

 

命令模式在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



 


 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值