Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Observer pattern - when to

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.

like image 762
JNovice Avatar asked Oct 11 '22 19:10

JNovice


1 Answers

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.

like image 171
Pace Avatar answered Oct 16 '22 06:10

Pace