命令模式实现

命令模式实现步骤

  1. 定义命令的执行者,里面执行具体的业务逻辑。
  2. 定义具体的命令,该对象中会将具体的命令执行者作为参数接收,调用操作。
  3. 定义命令的发布者,这个里面将命令作为参数传递。
  4. 定义具体实现类,调用命令发布者,将具体的命令传递进去。

案例

我们以客人去餐厅点餐作为例子。我们首先建立 net.haicoder.command 包。客人去餐厅点餐的时候,肯定有初始在准备者了,是命令的执行者,我们建立 CookService.java 类。

然后我们先把具体的菜单命令给实现 比如 MenuCommandService.javaMeatMenuCommandServiceImpl.javaPotatoesMenuCommandServiceImpl.java 类。还有命令发送者 CustomerService.java 以及 TestMain.java 类。文件创建完毕,具体目录结构如下:

05 命令模式代码结构类.png

CookService.java 代码如下:

package net.haicoder.command; /** * 厨师操作 */ public class CookService { public void cookPotatoes() { System.out.println("炒土豆丝"); } public void cookMeat() { System.out.println("炒肉丝"); } }

MenuCommandService.java 代码如下:

package net.haicoder.command; /** * 菜单 */ public interface MenuCommandService { void execute(); }

MeatMenuCommandServiceImpl.java代码如下:

package net.haicoder.command; public class MeatMenuCommandServiceImpl implements MenuCommandService { private CookService cookService = new CookService(); public void execute() { cookService.cookMeat(); } }

PotatoesMenuCommandServiceImpl.java 代码如下:

package net.haicoder.command; public class PotatoesMenuCommandServiceImpl implements MenuCommandService { private CookService cookService = new CookService(); public void execute() { cookService.cookPotatoes(); } }

CustomerService.java 代码如下:

package net.haicoder.command; /** * 客人点单 */ public class CustomerService { private MenuCommandService command; public CustomerService(MenuCommandService command) { this.command = command; } public void createOrder() { System.out.println("客人点单"); command.execute(); } }

TestMain.java 代码如下:

package net.haicoder.command; public class TestMain { public static void main(String[] args) { System.out.println("嗨客网(www.haicoder.net)"); MenuCommandService commandService = new MeatMenuCommandServiceImpl(); CustomerService customerService = new CustomerService(commandService); customerService.createOrder(); System.out.println("======华丽分割线=========="); customerService = new CustomerService(new PotatoesMenuCommandServiceImpl()); customerService.createOrder(); } }

代码运行结果如下:

06 命令模式执行结果.png

命令模式总结

设计模式命令模式将命令的发布者和执行者分离,将系统进行了很好的解耦,各司其职。