`
xieyaxiong
  • 浏览: 38983 次
  • 性别: Icon_minigender_1
  • 来自: 武汉
社区版块
存档分类
最新评论

design pattern——命令模式

 
阅读更多

 

针对问题:在软件系统中,“行为请求者”与“行为实现者”通常呈现一种“紧耦合”。但在某些场合,比如要对行为进行“记录、撤销/重做、事务”等处理,这种无法抵御变化的紧耦合是不合适的。在这种情况下,如何将“行为请求者”与“行为实现者”解耦?将一组行为抽象为对象,实现二者之间的松耦合。这就是命令模式。在命令模式上可以看到观察者模块和代理模块的影子,事实上就是两者的结合。

 

 

 

 

 

 

 

命令模式结构图:


 

 

 

 

 

 

命令模式实现代码:

 

 

/**
 * 命令接口
 * @author bruce
 *
 */
public interface Command {
	
	public void execute();

}




/**
 * 行为类
 * @author bruce
 *
 */
public class Receiver {
	
	public void action(){
		System.out.println("really doing something");
	}

}




/**
 * 命令实现类
 * @author bruce
 *
 */
public class ConcreteCommand implements Command{
	
	private Receiver receiver; //组合行为对象
	
	public ConcreteCommand(Receiver receiver){
		this.receiver=receiver;
	}

	public void execute() {
		// TODO Auto-generated method stub
		System.out.println("start");
		receiver.action();
	}
}





/**
 * 调用者对象
 * @author bruce
 *
 */
public class Invoker {
	
	private Command command;
	
	public void setCommand(Command command){
		this.command=command;
	}

	public void runCommand(){
		if(command==null)return;
		command.execute();
	}
	
}






/**
 * 测试
 * @author bruce
 *
 */

public class Client {
	
	public static void main(String[] args) {
		Receiver receiver=new Receiver();
		Command command=new ConcreteCommand(receiver);
		
		Invoker invoker=new Invoker();
		invoker.setCommand(command);
		invoker.runCommand();
		
		/**
		 * output://
		   start
		   really doing something
		 */
	}

}

 

 

  • 大小: 6.3 KB
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics