随着水果店推出的商品种类的增加,会有不同的水果榜单推出,每一种榜单都对应着响应的查询接口,如图中,热门商品榜-->热门查询,最新商品榜-->最新商品查询,优惠商品榜-->优惠商品查询。这种方式它的依赖关系太强。命令模式:将不符合抽象编程的调用,改造成符合的抽象编程
通过使用命令行模式,把直接请求的动作进行接口的包装,形成面向接口编程,进一步的完成解耦:
完成后,它的行为模式就变成了如下:
中间抽象出来了一层接口。对应的类图:
首先原始的提供查询服务的三个类:
/**
* 优惠商品查询
*/
public class DiscountHandler {
public String getDiscounts(){
System.out.println("返回优惠商品列表");
return "优惠商品列表";
}
}
/**
* 热门商品查询
*/
public class HotHandler {
public String getHots(){
System.out.println("返回热门商品列表");
return "热门商品列表";
}
}
/**
* 最新商品查询
*/
public class NewerHandler {
public String getNewers(){
System.out.println("返回最新商品列表");
return "最新商品列表";
}
}
三个原始类的包装命令行类:
/**
* 优惠商品查询包装命令
*/
public class DiscountCommand extends Command {
private DiscountHandler handler = new DiscountHandler();
@Override
public String execute() {
return handler.getDiscounts();
}
}
/**
* 热门商品查询包装命令
*/
public class HotCommand extends Command {
private HotHandler handler = new HotHandler();
@Override
public String execute() {
return handler.getHots();
}
}
/**
* 最新商品查询包装命令
*/
public class NewerCommand extends Command {
private NewerHandler handler = new NewerHandler();
@Override
public String execute() {
return handler.getNewers();
}
}
命令行接口:
public abstract class Command {
public abstract String execute();
}
/**
* 命令模式:将方法调用本身,包装成一个对象(命令对象)
* 订单支付过程
*/
public class ListView {
private Command command; //维持一个抽象命令对象的引用
//为功能键注入命令
public void setCommand(Command command) {
this.command = command;
}
//请求列表
public void getList() {
System.out.print("首页请求");
String result = command.execute();
System.out.println("当前列表:"+result);
}
}
调用对象:
/**
* 命令模式:将不符合抽象编程的调用,改造成符合的抽象编程
* 首页榜单
*/
public class CommandClient {
public static void main(String[] args) {
//三个命令,代表三个请求
Command command1,command2,command3;
command1 = new HotCommand();
command2 = new NewerCommand();
command3 = new DiscountCommand();
ListView listView;
listView = new ListView();
listView.setCommand(command2);
listView.getList();
}
}