任何人都可以与我分享一个听众模式的例子

时间:2011-12-18 10:26:58

标签: java

我正在学习一种叫做听众的设计模式。任何人都可以与我分享这种模式的一个例子。我不需要任何与GUI相关的内容,如JWT,谢谢

3 个答案:

答案 0 :(得分:6)

监听器模式与Observer非常接近。基本上你只是允许其他对象“听”你的对象。因此,您需要维护这些侦听器的列表,并在需要时通知它们。

这样的事情:

public class MyClass {
   public static interface Listener {
      public void onNotify();
   }

   private List<Listener> listeners = new ArrayList<Listener>();

   // addListener and removeListener methods omitted.

   public void doSomething() {
      // do something that listeners should be notified of.

      // notify listeners like this:
      for (Listener l : listeners) {
         l.onNotify();
      }
   }
}

希望有道理:)

答案 1 :(得分:1)

以下是Java中模式的使用示例,因为您不需要特定的内容......

public class MyButton extends JButton implements ActionListener {
    public MyButton() {
        addActionListener(this);
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        // omgwtfbbqroflolkthxbai
    }
}

答案 2 :(得分:1)

听众模式实际上不属于四人一组list的设计模式。但是,侦听器模式只是查看观察者模式的另一种方式。这个Wikipedia article包含了用Java编写的观察者模式解决方案的一个很好的例子。