博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
设计模式 指令模式_指令设计模式
阅读量:2527 次
发布时间:2019-05-11

本文共 9156 字,大约阅读时间需要 30 分钟。

设计模式 指令模式

Command Pattern is one of the Behavioral Design Pattern. Command design pattern is used to implement loose coupling in a request-response model.

命令模式是行为设计​​模式之一。 命令设计模式用于在请求-响应模型中实现松耦合

命令模式 (Command Pattern)

In command pattern, the request is send to the invoker and invoker pass it to the encapsulated command object.

在命令模式中,请求被发送到invoker ,调用者将其传递给封装的command对象。

Command object passes the request to the appropriate method of Receiver to perform the specific action.

命令对象将请求传递给Receiver的适当方法以执行特定操作。

The client program create the receiver object and then attach it to the Command. Then it creates the invoker object and attach the command object to perform an action.

客户端程序创建接收器对象,然后将其附加到命令。 然后,它创建调用者对象并附加命令对象以执行操作。

Now when client program executes the action, it’s processed based on the command and receiver object.

现在,当客户端程序执行动作时,将根据命令和接收器对象对其进行处理。

命令设计模式示例 (Command Design Pattern Example)

We will look at a real life scenario where we can implement Command pattern. Let’s say we want to provide a File System utility with methods to open, write and close file. This file system utility should support multiple operating systems such as Windows and Unix.

我们将看一个可以实现Command模式的现实生活场景。 假设我们要为File System实用程序提供打开,写入和关闭文件的方法。 该文件系统实用程序应支持多种操作系统,例如Windows和Unix。

To implement our File System utility, first of all we need to create the receiver classes that will actually do all the work.

要实现我们的文件系统实用程序,首先,我们需要创建将实际完成所有工作的接收器类。

Since we code in terms of , we can have FileSystemReceiver interface and it’s implementation classes for different operating system flavors such as Windows, Unix, Solaris etc.

由于我们中的编码,因此我们可以拥有FileSystemReceiver接口,并且它是用于不同操作系统风格的实现类,例如Windows,Unix,Solaris等。

命令模式接收器类 (Command Pattern Receiver Classes)

package com.journaldev.design.command;public interface FileSystemReceiver {	void openFile();	void writeFile();	void closeFile();}

FileSystemReceiver interface defines the contract for the implementation classes. For simplicity, I am creating two flavors of receiver classes to work with Unix and Windows systems.

FileSystemReceiver接口定义实现类的协定。 为简单起见,我创建了两种类型的接收器类以与Unix和Windows系统一起使用。

package com.journaldev.design.command;public class UnixFileSystemReceiver implements FileSystemReceiver {	@Override	public void openFile() {		System.out.println("Opening file in unix OS");	}	@Override	public void writeFile() {		System.out.println("Writing file in unix OS");	}	@Override	public void closeFile() {		System.out.println("Closing file in unix OS");	}}
package com.journaldev.design.command;public class WindowsFileSystemReceiver implements FileSystemReceiver {	@Override	public void openFile() {		System.out.println("Opening file in Windows OS");			}	@Override	public void writeFile() {		System.out.println("Writing file in Windows OS");	}	@Override	public void closeFile() {		System.out.println("Closing file in Windows OS");	}}

Did you noticed the Override annotation and if you wonder why it’s used, please read and .

您是否注意到Override注释,并且如果您想知道为什么使用它,请阅读并 。

Now that our receiver classes are ready, we can move to implement our Command classes.

现在我们的接收器类已经准备好了,我们可以开始实现Command类了。

命令模式接口和实现 (Command Pattern Interface and Implementations)

We can use to create our base Command, it’s a design decision and depends on your requirement.

我们可以使用来创建基本Command,这是设计决定,取决于您的要求。

We are going with interface because we don’t have any default implementations.

我们要使用接口,因为我们没有任何默认实现。

package com.journaldev.design.command;public interface Command {	void execute();}

Now we need to create implementations for all the different types of action performed by the receiver. Since we have three actions we will create three Command implementations. Each Command implementation will forward the request to the appropriate method of receiver.

现在,我们需要为接收器执行的所有不同类型的操作创建实现。 由于我们有三个动作,因此我们将创建三个Command实现。 每个Command实现都会将请求转发到适当的接收方方法。

package com.journaldev.design.command;public class OpenFileCommand implements Command {	private FileSystemReceiver fileSystem;		public OpenFileCommand(FileSystemReceiver fs){		this.fileSystem=fs;	}	@Override	public void execute() {		//open command is forwarding request to openFile method		this.fileSystem.openFile();	}}
package com.journaldev.design.command;public class CloseFileCommand implements Command {	private FileSystemReceiver fileSystem;		public CloseFileCommand(FileSystemReceiver fs){		this.fileSystem=fs;	}	@Override	public void execute() {		this.fileSystem.closeFile();	}}
package com.journaldev.design.command;public class WriteFileCommand implements Command {	private FileSystemReceiver fileSystem;		public WriteFileCommand(FileSystemReceiver fs){		this.fileSystem=fs;	}	@Override	public void execute() {		this.fileSystem.writeFile();	}}

Now we have receiver and command implementations ready, so we can move to implement the invoker class.

现在我们已经准备好接收器和命令实现,因此可以继续执行调用程序类。

命令模式调用者类 (Command Pattern Invoker Class)

Invoker is a simple class that encapsulates the Command and passes the request to the command object to process it.

Invoker是一个简单的类,它封装Command,并将请求传递给Command对象以对其进行处理。

package com.journaldev.design.command;public class FileInvoker {	public Command command;		public FileInvoker(Command c){		this.command=c;	}		public void execute(){		this.command.execute();	}}

Our file system utility implementation is ready and we can move to write a simple command pattern client program. But before that I will provide a utility method to create the appropriate FileSystemReceiver object.

我们的文件系统实用程序实现已经准备就绪,我们可以继续编写简单的命令模式客户端程序。 但是在此之前,我将提供一种实用程序方法来创建适当的FileSystemReceiver对象。

Since we can use , we will use this or else we can use to return appropriate type based on the input.

由于我们可以使用 ,因此将使用此类,否则我们可以使用来基于输入返回适当的类型。

package com.journaldev.design.command;public class FileSystemReceiverUtil {		public static FileSystemReceiver getUnderlyingFileSystem(){		 String osName = System.getProperty("os.name");		 System.out.println("Underlying OS is:"+osName);		 if(osName.contains("Windows")){			 return new WindowsFileSystemReceiver();		 }else{			 return new UnixFileSystemReceiver();		 }	}	}

Let’s move now to create our command pattern example client program that will consume our file system utility.

现在开始创建将使用我们的文件系统实用程序的命令模式示例客户端程序。

package com.journaldev.design.command;public class FileSystemClient {	public static void main(String[] args) {		//Creating the receiver object		FileSystemReceiver fs = FileSystemReceiverUtil.getUnderlyingFileSystem();				//creating command and associating with receiver		OpenFileCommand openFileCommand = new OpenFileCommand(fs);				//Creating invoker and associating with Command		FileInvoker file = new FileInvoker(openFileCommand);				//perform action on invoker object		file.execute();				WriteFileCommand writeFileCommand = new WriteFileCommand(fs);		file = new FileInvoker(writeFileCommand);		file.execute();				CloseFileCommand closeFileCommand = new CloseFileCommand(fs);		file = new FileInvoker(closeFileCommand);		file.execute();	}}

Notice that client is responsible to create the appropriate type of command object. For example if you want to write a file you are not supposed to create CloseFileCommand object.

注意,客户端负责创建适当类型的命令对象。 例如,如果要编写文件,则不应创建CloseFileCommand对象。

Client program is also responsible to attach receiver to the command and then command to the invoker class.

客户端程序还负责将接收方附加到命令,然后将命令附加到调用方类。

Output of the above command pattern example program is:

上面的命令模式示例程序的输出为:

Underlying OS is:Mac OS XOpening file in unix OSWriting file in unix OSClosing file in unix OS

命令模式类图 (Command Pattern Class Diagram)

Here is the class diagram for our file system utility implementation.

这是我们的文件系统实用程序实现的类图。

命令模式要点 (Command Pattern Important Points)

  • Command is the core of command design pattern that defines the contract for implementation.

    命令是命令设计模式的核心,它定义了实现合同。
  • Receiver implementation is separate from command implementation.

    接收器实现与命令实现是分开的。
  • Command implementation classes chose the method to invoke on receiver object, for every method in receiver there will be a command implementation. It works as a bridge between receiver and action methods.

    命令实现类选择了要在接收器对象上调用的方法,因为接收器中的每个方法都会有一个命令实现。 它充当接收方和操作方法之间的桥梁。
  • Invoker class just forward the request from client to the command object.

    Invoker类仅将来自客户端的请求转发到命令对象。
  • Client is responsible to instantiate appropriate command and receiver implementation and then associate them together.

    客户负责实例化适当的命令和接收器实现,然后将它们关联在一起。
  • Client is also responsible for instantiating invoker object and associating command object with it and execute the action method.

    客户端还负责实例化调用者对象并将命令对象与其关联,并执行action方法。
  • Command design pattern is easily extendible, we can add new action methods in receivers and create new Command implementations without changing the client code.

    命令设计模式易于扩展,我们可以在接收器中添加新的操作方法并创建新的Command实现,而无需更改客户端代码。
  • The drawback with Command design pattern is that the code gets huge and confusing with high number of action methods and because of so many associations.

    Command设计模式的缺点在于,由于大量的关联,代码变得庞大且与大量的操作方法混淆。

命令设计模式JDK示例 (Command Design Pattern JDK Example)

(java.lang.Runnable) and Swing Action (javax.swing.Action) uses command pattern.

(java.lang.Runnable)和Swing Action(javax.swing.Action)使用命令模式。

翻译自:

设计模式 指令模式

转载地址:http://zwlzd.baihongyu.com/

你可能感兴趣的文章
点云PCL中小细节
查看>>
铁路信号基础
查看>>
RobotFramework自动化2-自定义关键字
查看>>
[置顶] 【cocos2d-x入门实战】微信飞机大战之三:飞机要起飞了
查看>>
BABOK - 需求分析(Requirements Analysis)概述
查看>>
第43条:掌握GCD及操作队列的使用时机
查看>>
Windows autoKeras的下载与安装连接
查看>>
CMU Bomblab 答案
查看>>
微信支付之异步通知签名错误
查看>>
2016 - 1 -17 GCD学习总结
查看>>
linux安装php-redis扩展(转)
查看>>
Vue集成微信开发趟坑:公众号以及JSSDK相关
查看>>
技术分析淘宝的超卖宝贝
查看>>
i++和++1
查看>>
react.js
查看>>
P1313 计算系数
查看>>
NSString的长度比较方法(一)
查看>>
Azure云服务托管恶意软件
查看>>
My安卓知识6--关于把项目从androidstudio工程转成eclipse工程并导成jar包
查看>>
旧的起点(开园说明)
查看>>