个人博客
http://www.milovetingting.cn
命令模式
模式介绍
命令模式是行为型设计模式之一。
模式定义
将请求封装成一个对象,从而让用户使用不同的请求把客户端参数化;对请求排除或者记录请求日志,以及支持可撤销操作。
使用场景
需要抽象出待执行的动作,然后以参数的形式提供出来
 
在不同的时刻指定、排列和执行请求。
 
需要支持取消操作。
 
支持修改日志功能。
 
需要支持事务操作。
 
简单使用
定义命令接收者,即执行者
1 2 3 4 5 6 7 8 9 10 11
   | public class Receiver { 	 	
 
  	public void action() 	{ 		System.out.println("执行具体的操作"); 	}
  }
  | 
 
定义命令的接口类
1 2 3 4 5 6 7 8
   | public interface Command { 	 	
 
  	public void execute();
  }
  | 
 
定义命令的实现类
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
   | public class CommandImpl implements Command {
  	private Receiver receiver;
  	public CommandImpl(Receiver receiver) { 		super(); 		this.receiver = receiver; 	}
  	@Override 	public void execute() { 		receiver.action(); 	}
  }
  | 
 
定义请求者
1 2 3 4 5 6 7 8 9 10 11 12 13 14
   | public class Invoker {
  	private Command command;
  	public Invoker(Command command) { 		super(); 		this.command = command; 	}
  	public void action() { 		command.execute(); 	}
  }
  | 
 
调用
1 2 3 4 5 6
   | public static void main(String[] args) { 		Receiver receiver = new Receiver(); 		Command command = new CommandImpl(receiver); 		Invoker invoker = new Invoker(command); 		invoker.action(); 	}
  |