我们以客人去餐厅点餐作为例子。我们首先建立 net.haicoder.command
包。客人去餐厅点餐的时候,肯定有初始在准备者了,是命令的执行者,我们建立 CookService.java
类。
然后我们先把具体的菜单命令给实现 比如 MenuCommandService.java
、MeatMenuCommandServiceImpl.java
、PotatoesMenuCommandServiceImpl.java
类。还有命令发送者 CustomerService.java
以及 TestMain.java
类。文件创建完毕,具体目录结构如下:
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();
}
}
代码运行结果如下:
命令模式总结