Home  >  Article  >  Java  >  Sample code for implementing command mode in Java

Sample code for implementing command mode in Java

黄舟
黄舟Original
2017-03-11 11:21:362349browse

In software systems, "Behavior requester" and "Behavior implementer" usually present a kind of "Tight coupling". But in some situations, such as "recording, undo/redo, transaction" and other processing of behaviors, this kind of tight coupling that cannot resist changes is inappropriate. In this case, how to decouple the "behavior requester" from the "behavior implementer"? Abstract a set of behaviors into objects , achieve loose coupling between the two . This isCommand Pattern

Class Diagram



#

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();
	}
}

The above is the detailed content of Sample code for implementing command mode in Java. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn