首页 > 代码库 > Java 实现命令(Command)模式

Java 实现命令(Command)模式

类图


public interface ICommand {
	void execute();
}

public class ConcreteCommand implements ICommand {
	private Receiver receiver;

	public ConcreteCommand(Receiver receiver) {
		this.receiver = receiver;
	}

	@Override
	public void execute() {
		this.receiver.action();
	}

}

public class Receiver {
	public void action() {
		System.out.println("receiver do something");
	}
}

public class Invoker {
	private ICommand command;
	
	public Invoker(ICommand command) {
		this.command = command;
	}
	
	public void invoke() {
		this.command.execute();
	}
}

/*
 * 命令(Command)模式
 * 请求与执行 分离
 * 可以多个命令接口的实现类,隐藏真实的被调用方
 */
public class Test {
	public static void main(String[] args) {
		Receiver receiver = new Receiver();//真正的执行者
		ICommand command = new ConcreteCommand(receiver);//用于的隔离的命令
		Invoker invoker = new Invoker(command );//调用者
		invoker.invoke();
	}
}


Java 实现命令(Command)模式