命令模式属于行为型模式。
命令模式将多组功能包装起来,以对象形式调用内部的方法
Cook类就是指多组功能中的其中一组功能
java
public class Cook {
public void makeFriedRice() {
System.out.println("厨师正在做炒饭。");
}
public void makeNoodles() {
System.out.println("厨师正在做面条。");
}
}
不同的命令对象将功能封装起来
java
public interface Command {
void execute();
}
java
public class OrderFriedRiceCommand implements Command{
private Cook cook;
public OrderFriedRiceCommand(Cook cook) {
this.cook = cook;
}
@Override
public void execute() {
cook.makeFriedRice();
}
}
java
public class OrderNoodlesCommand implements Command{
private Cook cook;
public OrderNoodlesCommand(Cook cook) {
this.cook = cook;
}
@Override
public void execute() {
cook.makeNoodles();
}
}
调用者,调用不同封装起来的对象
java
public class Waiter {
private Command command;
public void setCommand(Command command) {
this.command = command;
}
public void placeOrder() {
if (command!= null) {
command.execute();
}
}
}
测试
java
public class Main {
public static void main(String[] args) {
Cook cook = new Cook();
OrderFriedRiceCommand orderFriedRiceCommand = new OrderFriedRiceCommand(cook);
OrderNoodlesCommand orderNoodlesCommand = new OrderNoodlesCommand(cook);
Waiter waiter = new Waiter();
waiter.setCommand(orderNoodlesCommand);
waiter.placeOrder();
waiter.setCommand(orderFriedRiceCommand);
waiter.placeOrder();
}
}
。。。。怎么说呢,感觉有点鸡肋,他把好几个对象中的方法,提取出来集合到一个对象中,如果集合中需要添加其他对象的方法,就又得再修改。虽然解耦了调用方和接受方,但是随着功能越来越复杂类会越来越多