观察者模式-何时 [英] Observer pattern - when to

查看:100
本文介绍了观察者模式-何时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们一直在工作地点来回争论使用观察者模式来解决其中一个问题.我以某种方式闻到过度使用"的声音,但是愿意接受一些想法.所以要求是

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.

为此,我们创建了一个OrderCancel类(它是Observer模式习语中的Subject)和LineItemCancel类(它是Observer).我们还有一个带有cancelOrders(Listorders)方法的OrderManager类,该类实例化OrderCancel和相应的LineItemCancel对象,然后将它们全部注册到OrderCancel中.代码如下.

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.

期待听到您的想法.

推荐答案

观察者模式仅在减少耦合时才有用.在这个示例中,我看不到耦合的减少,所以我会说它被过度使用了.

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.

这篇关于观察者模式-何时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆