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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With