我们将使用责任链模式和装饰者模式的组合。
考虑一个简化的餐厅订单处理系统,其中包括服务员(Waiter)、厨师(Chef)和收银员(Cashier)。订单从服务员开始,然后传递给厨师,最后到达收银员。订单对象包含了顾客的点菜信息。
订单类(Order):
public class Order {
private String customerName;
private String dishName;
public Order(String customerName, String dishName) {
this.customerName = customerName;
this.dishName = dishName;
}
public String getCustomerName() {
return customerName;
}
public String getDishName() {
return dishName;
}
}
责任链模式:服务员、厨师和收银员
// 处理订单的接口
public interface OrderHandler {
void handleOrder(Order order);
}
// 服务员
public class Waiter implements OrderHandler {
private OrderHandler nextHandler;
public Waiter(OrderHandler nextHandler) {
this.nextHandler = nextHandler;
}
@Override
public void handleOrder(Order order) {
System.out.println("Waiter takes order from " + order.getCustomerName());
if (nextHandler != null) {
nextHandler.handleOrder(order);
}
}
}
// 厨师
public class Chef implements OrderHandler {
private OrderHandler nextHandler;
public Chef(OrderHandler nextHandler) {
this.nextHandler = nextHandler;
}
@Override
public void handleOrder(Order order) {
System.out.println("Chef prepares dish: " + order.getDishName());
if (nextHandler != null) {
nextHandler.handleOrder(order);
}
}
}
// 收银员
public class Cashier implements OrderHandler {
@Override
public void handleOrder(Order order) {
System.out.println("Cashier processes payment for " + order.getDishName());
}
}
装饰者模式:为订单添加额外信息
// 装饰者抽象类
public abstract class OrderDecorator implements OrderHandler {
protected OrderHandler nextHandler;
public OrderDecorator(OrderHandler nextHandler) {
this.nextHandler = nextHandler;
}
@Override
public abstract void handleOrder(Order order);
}
// 装饰者:添加打包信息
public class PackagingDecorator extends OrderDecorator {
public PackagingDecorator(OrderHandler nextHandler) {
super(nextHandler);
}
@Override
public void handleOrder(Order order) {
System.out.println("Packaging decorator adds packaging for " + order.getDishName());
if (nextHandler != null) {
nextHandler.handleOrder(order);
}
}
}
客户端代码:
public class Client {
public static void main(String[] args) {
// 构建责任链:服务员 -> 厨师 -> 装饰者(打包) -> 收银员
OrderHandler cashier = new Cashier();
OrderHandler packagingDecorator = new PackagingDecorator(cashier);
OrderHandler chef = new Chef(packagingDecorator);
OrderHandler waiter = new Waiter(chef);
// 创建订单
Order order = new Order("John", "Pizza");
// 提交订单给责任链
waiter.handleOrder(order);
}
}
在这个例子中,责任链模式帮助我们实现了订单处理的链式调用,而装饰者模式允许我们动态地为订单添加额外的信息(比如打包)。通过这样的设计,我们可以更容易地扩展系统、添加新的处理者或者装饰者,而不必修改现有的类。