设计模式-命令模式
命令模式属于行为型模式。
命令模式将多组功能包装起来,以对象形式调用内部的方法
Cook类就是指多组功能中的其中一组功能
public class Cook {
public void makeFriedRice() {
System.out.println("厨师正在做炒饭。");
}
public void makeNoodles() {
System.out.println("厨师正在做面条。");
}
}
不同的命令对象将功能封装起来
public interface Command {
void execute();
}
public class OrderFriedRiceCommand implements Command{
private Cook cook;
public OrderFriedRiceCommand(Cook cook) {
this.cook = cook;
}
@Override
public void execute() {
cook.makeFriedRice();
}
}
public class OrderNoodlesCommand implements Command{
private Cook cook;
public OrderNoodlesCommand(Cook cook) {
this.cook = cook;
}
@Override
public void execute() {
cook.makeNoodles();
}
}
调用者,调用不同封装起来的对象
public class Waiter {
private Command command;
public void setCommand(Command command) {
this.command = command;
}
public void placeOrder() {
if (command!= null) {
command.execute();
}
}
}
测试
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();
}
}
。。。。怎么说呢,感觉有点鸡肋,他把好几个对象中的方法,提取出来集合到一个对象中,如果集合中需要添加其他对象的方法,就又得再修改。虽然解耦了调用方和接受方,但是随着功能越来越复杂类会越来越多
原文地址:https://blog.csdn.net/weixin_51722520/article/details/143684634
免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!