【设计模式】命令模式

【设计模式】命令模式

  • 封装具备“命令”特征的操作------同类操作

  • decouple the remote from devices

Invoker:发送请求

Receiver:接受请求

  1. define an abstraction that involves basic operations to devices

  2. Invoker sends request through interfaces. #通过接口请求

  3. Receiver reacts request according to its own type #通过具体类型回应

the client uses the invoker class ---------> main()

定义:

命令模式/动作模式/事务模式

将一个请求封装成一个对象,从而使我们可用不同的请求对client进行参数化

对请求进行排队或者记录其日志,以及支持可撤销的操作。

Encapsulate a request as an object, thereby letting you parameterize clients with different requests, queue or log requests, and support undoable operations.

UML图:
image-20191111230253513

引用: https://blog.csdn.net/wglla/article/details/52225571 uml图六种箭头的含义

前段时间学的,忘记了,这里回顾加深理解一下。

以电视和空调的开关为例,大致框架如下:

tv/ac中的open和close方法相当于Receiver中的action。

// command pattern fuxi

interface AbstractCommand{
	void execute();
}

//----the reveiver class tv / ac
public class TV{
	open();
	close();
}

public class AC{
	turnOn();
	turnOff();
}

//以tv open的操作为例
public class TVOpenCommand implements AbstractCommand{
	private TV tv;

	public TVOpenCommand(TV tv){
		this.tv = tv;
	}
	public void execute(){
		tv.open();
	}
}

//其他类似
public class TVCloseCommand implements AbstractCommand{}
public class ACOpenCommand implements AbstractCommand{}
public class ACCloseCommand implements AbstractCommand{}


public class RemoteController{
	AbstractCommand openCommand;
	AbstractCommand closeCommand;
	AbstractCommand changeCommand;

	public RemoteController(TVOpenCommand openCommand){
		//initial...
		this.openCommand = openCommand;
		...
	}

	public void open(){
		openCommand.execute();
	}
	...
}

关于宏命令:

一个命令,要进行一系列的操作,这些操作每次都必须有并且都执行。

//宏命令
public class MacroCommand implements AbstractCommand {
  
  AbstractCommand[] commands;

  public MacroCommand( AbstractCommand[] commands){ 
    this.commands = commands; 
  }

  public void execute(){
    for( int i=0; i < commands.length; i++ ){
      commands[i].execute();
    }
  }
}

优点:

1 降低系统的耦合度

  • 调用者和接受者不直接交互

  • invoker不需要知道receiver的存在,反之亦然

2 容易加入新的命令

3 容易设计命令队列以及宏命令

  • 实现命令的批处理

缺点:

  • 具体命令类较多,可能难于维护。
原文地址:https://www.cnblogs.com/christy99cc/p/11839264.html