问题
We have been arguing back and forth at my work place about the use of the Observer pattern for one of the problems. I somehow smell "overuse" but am open to ideas. So the requirement is
We have a hierarchy of objects -> an order and multiple line items in the order. When the order is cancelled, all the line items need to cancelled.
To do this, we have created a OrderCancel class which is the Subject in the Observer pattern idiom and LineItemCancel class which is the Observer. We also have a OrderManager class with a cancelOrders(List orders) method which instantiates the OrderCancel and the corresponding LineItemCancel objects and then registers them all in the OrderCancel. The code is as follows.
public class OrderManager {
public void cancelOrders(List<Order> orders){
for(Order order :orders){
OrderCancel orderCancel = new OrderCancel(order);
Listener listener = new LineItemCancel(order);
orderCancel.addListeners(listener);
orderCancel.cancel();
}
}
}
public class OrderCancel implements Subject {
private List<Listener> listeners = new ArrayList<Listener>();
private Order order;
public OrderCancel(Order order) {
this.order = order;
}
@Override
public void addListeners(Listener listener) {
listeners.add(listener);
}
@Override
public void notifyListeners() {
for(Listener listener : listeners){
listener.update();
}
}
public void cancel() {
notifyListeners();
cancelOrder();
}
private void cancelOrder() {
}
}
public class LineItemCancel implements Listener {
private Order order;
public LineItemCancel(Order order) {
this.order = order;
}
@Override
public void update() {
cancelLineItem();
}
private void cancelLineItem() {
}
}
I am convinced this is improper usage. But I am not able to convince the designers of this class. I am trying to figure out myself if this is right as the designer is one of the architects at work.
Looking forward to hear your thoughts.
回答1:
The Observer pattern is only useful when it reduces coupling. I don't see any reduction of coupling in this example so I would say it is overuse.
回答2:
I agree w/ @Pace, definitely doesn't reduce coupling, definitely overuse. My question is that in your example, the simplest approach semas to be to have the Order cancel its own LineItems when you cancel it; is there a good reason not to do that for your app?
来源:https://stackoverflow.com/questions/6307419/observer-pattern-when-to