9

在设计具有生产者/消费者关系的两个类时,如何避免循环依赖?这里 ListenerImpl 需要一个对 Broadcaster 的引用才能注册/注销自己,而 Broadcaster 需要一个对 Listeners 的引用才能发送消息。这个例子是用 Java 编写的,但它可以应用于任何 OO 语言。

public interface Listener {
  void callBack(Object arg);
}
public class ListenerImpl implements Listener {
  public ListenerImpl(Broadcaster b) { b.register(this); }
  public void callBack(Object arg) { ... }
  public void shutDown() { b.unregister(this); }
}
public class Broadcaster {
  private final List listeners = new ArrayList();
  public void register(Listener lis) { listeners.add(lis); }
  public void unregister(Listener lis) {listeners.remove(lis); }
  public void broadcast(Object arg) { for (Listener lis : listeners) { lis.callBack(arg); } }
}
4

6 回答 6

9

我不认为这是一个循环依赖。

听众什么都不依赖。

ListenerImpl 依赖于 Listener 和 Broadcaster

Broadcaster 依赖于 Listener。

        Listener
       ^        ^
      /          \
     /            \
Broadcaster <--  ListenerImpl

所有箭头都在 Listener 处结束。没有循环。所以,我觉得你没问题。

于 2008-09-29T16:23:50.900 回答
7

任何面向对象语言?好的。这是 CLOS 中的十分钟版本。

广播框架

(defclass broadcaster ()
  ((listeners :accessor listeners
              :initform '())))

(defgeneric add-listener (broadcaster listener)
  (:documentation "Add a listener (a function taking one argument)
  to a broadcast's list of interested parties"))

(defgeneric remove-listener (broadcaster listener)
  (:documentation "Reverse of add-listener"))

(defgeneric broadcast (broadcaster object)
  (:documentation "Broadcast an object to all registered listeners"))

(defmethod add-listener (broadcaster listener)
  (pushnew listener (listeners broadcaster)))

(defmethod remove-listener (broadcaster listener)
  (let ((listeners (listeners broadcaster)))
    (setf listeners (remove listener listeners))))

(defmethod broadcast (broadcaster object)
  (dolist (listener (listeners broadcaster))
    (funcall listener object)))

示例子类

(defclass direct-broadcaster (broadcaster)
  ((latest-broadcast :accessor latest-broadcast)
   (latest-broadcast-p :initform nil))
  (:documentation "I broadcast the latest broadcasted object when a new listener is added"))

(defmethod add-listener :after ((broadcaster direct-broadcaster) listener)
  (when (slot-value broadcaster 'latest-broadcast-p)
    (funcall listener (latest-broadcast broadcaster))))

(defmethod broadcast :after ((broadcaster direct-broadcaster) object)
  (setf (slot-value broadcaster 'latest-broadcast-p) t)
  (setf (latest-broadcast broadcaster) object))

示例代码

Lisp> (let ((broadcaster (make-instance 'broadcaster)))
        (add-listener broadcaster 
                      #'(lambda (obj) (format t "I got myself a ~A object!~%" obj)))
        (add-listener broadcaster 
                      #'(lambda (obj) (format t "I has object: ~A~%" obj)))
        (broadcast broadcaster 'cheezburger))

I has object: CHEEZBURGER
I got myself a CHEEZBURGER object!

Lisp> (defparameter *direct-broadcaster* (make-instance 'direct-broadcaster))
      (add-listener *direct-broadcaster*
                  #'(lambda (obj) (format t "I got myself a ~A object!~%" obj)))
      (broadcast *direct-broadcaster* 'kitty)

I got myself a KITTY object!

Lisp> (add-listener *direct-broadcaster*
                    #'(lambda (obj) (format t "I has object: ~A~%" obj)))

I has object: KITTY

不幸的是,Lisp 通过消除对它们的需求解决了大多数设计模式问题(例如您的问题)。

于 2008-09-29T17:09:13.773 回答
4

与 Herms 的回答相反,我确实看到了一个循环。这不是依赖循环,而是引用循环:LI 保存 B 对象,B 对象保存(一个数组)LI 对象。它们不容易自由,需要注意确保它们在可能的情况下自由。

一种解决方法是让 LI 对象持有对广播者的 WeakReference。从理论上讲,如果广播公司已经离开,无论如何都没有什么可注销的,所以您的注销将简单地检查是否有广播公司要注销,如果有就这样做。

于 2008-09-29T17:57:33.827 回答
0

我不是 java 开发者,但像这样:

public class ListenerImpl implements Listener {
  public Foo() {}
  public void registerWithBroadcaster(Broadcaster b){ b.register(this); isRegistered = true;}
  public void callBack(Object arg) { if (!isRegistered) throw ... else ... }
  public void shutDown() { isRegistered = false; }
}

public class Broadcaster {
  private final List listeners = new ArrayList();
  public void register(Listener lis) { listeners.add(lis); }
  public void unregister(Listener lis) {listeners.remove(lis); }
  public void broadcast(Object arg) { for (Listener lis : listeners) { if (lis.isRegistered) lis.callBack(arg) else unregister(lis); } }
}
于 2008-09-29T16:28:27.317 回答
0

使用弱引用打破循环。

看到这个答案

于 2008-10-02T09:35:41.247 回答
0

这是 Lua 中的一个示例(我在这里使用我自己的Oop 库,请参阅代码中对“对象”的引用)。

就像在 Mikael Jansson 的 CLOS 示例中一样,您可以直接使用函数,无需定义侦听器(注意使用 '...',它是 Lua 的可变参数):

Broadcaster = Object:subclass()

function Broadcaster:initialize()
    self._listeners = {}
end

function Broadcaster:register(listener)
    self._listeners[listener] = true
end

function Broadcaster:unregister(listener)
    self._listeners[listener] = nil
end
function Broadcaster:broadcast(...)
    for listener in pairs(self._listeners) do
        listener(...)
    end
end

坚持你的实现,这是一个我猜可以用任何动态语言编写的示例:

--# Listener
Listener = Object:subclass()
function Listener:callback(arg)
    self:subclassResponsibility()
end

--# ListenerImpl
function ListenerImpl:initialize(broadcaster)
    self._broadcaster = broadcaster
    broadcaster:register(this)
end
function ListenerImpl:callback(arg)
    --# ...
end
function ListenerImpl:shutdown()
    self._broadcaster:unregister(self)
end

--# Broadcaster
function Broadcaster:initialize()
    self._listeners = {}
end
function Broadcaster:register(listener)
    self._listeners[listener] = true
end
function Broadcaster:unregister(listener)
    self._listeners[listener] = nil
end
function Broadcaster:broadcast(arg)
    for listener in pairs(self._listeners) do
        listener:callback(arg)
    end
end
于 2008-11-28T09:50:32.323 回答