Home > Java > javaTutorial > body text

Sample code for implementing command mode in Java

黄舟
Release: 2017-03-11 11:21:36
Original
2354 people have browsed it

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();
}
Copy after login
public class ConcreteCommand implements ICommand {
	private Receiver receiver;

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

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

}
Copy after login
public class Receiver {
	public void action() {
		System.out.println("receiver do something");
	}
}
Copy after login
public class Invoker {
	private ICommand command;
	
	public Invoker(ICommand command) {
		this.command = command;
	}
	
	public void invoke() {
		this.command.execute();
	}
}
Copy after login
/*
 * 命令(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();
	}
}
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!