欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

设计模式——命令模式

程序员文章站 2024-02-07 22:53:40
...

1 简介

命令模式(Command Pattern)定义:将一个请求封装为一个对象,从而使我们可用不同的请求对客户进行参数化;对请求排队或者记录请求日志,以及支持可撤销的操作。

命令模式的本质是对命令进行封装,将发出命令的责任和执行命令的责任分开,使得请求方不必知道接受方的接口,更不必知道请求是怎么被接受、操作是否被执行、何时被执行,以及是怎么被执行的。

设计模式——命令模式

设计模式——命令模式

2 代码

(1)接受者(Reciever)

public class Receiver {
	public void action() {
		System.out.println("执行命令");
	}
}

(2)抽象命令类(Command)

public abstract class Command {
	public abstract void execute();
}

(3)具体命令类(ConcreteCommand)

public class ConcreteCommand extends Command{
	private Receiver receiver=new Receiver();
	
	@Override
	public void execute() {
		receiver.action();
	}
}

(4)调用者(Invoker)

public class Invoker {
	private Command command;
	public Invoker(Command command) {
		this.command=command;
	}
	
	public void setCommand(Command command) {
		this.command=command;
	}
	
	public void call() {
		command.execute();
	}
}

(5)客户端(Client)

public class Client {

	public static void main(String[] args) {
		Invoker invoker=new Invoker(new ConcreteCommand());
		invoker.call();
	}
}

3 案例分析

设计模式——命令模式

(1)接受者(TV)

public class TV {
	public void open() {
		System.out.println("打开电视机");
	}
	
	public void changeChannel() {
		System.out.println("切换电视频道");
	}
	
	public void close() {
		System.out.println("关闭电视机");
	}
}

(2)抽象命令类(Command)

public abstract class Command {
	protected TV tv;
	
	Command(TV tv){
		this.tv=tv;
	}
	public abstract void execute();
}

(3)具体命令类(OpenCommand、ChangeCommand、CloseCommand)

public class OpenCommand extends Command{
	OpenCommand(TV tv){
		super(tv);
	}
	
	@Override
	public void execute() {
		tv.open();
	}
}

public class ChangeCommand extends Command{
	ChangeCommand(TV tv){
		super(tv);
	}
	
	@Override
	public void execute() {
		tv.changeChannel();
	}
}

public class CloseCommand extends Command{
	CloseCommand(TV tv){
		super(tv);
	}
	
	@Override
	public void execute() {
		tv.close();
	}
}

(4)调用者(Controller)

public class Controller {
	private Command openCommand,closeCommand,changeCommand;
	public Controller(Command op,Command cl,Command ch) {
		openCommand=op;
		changeCommand=ch;
		closeCommand=cl;
	}
	
	public void open() {
		openCommand.execute();
	}
	
	public void change() {
		changeCommand.execute();
	}
	
	public void close() {
		closeCommand.execute();
	}
}

(5)客户端(Client)

public class Client {

	public static void main(String[] args) {
		TV tv=new TV();
		Command openCommand=new OpenCommand(tv);
		Command closeCommand=new CloseCommand(tv);
		Command changeCommand=new ChangeCommand(tv);
		Controller controller=new Controller(openCommand,closeCommand,changeCommand);
		controller.open();
		controller.change();
		controller.close();
	}
}