7

设计模式学习(十三):观察者模式 - Grey Zeng

 1 year ago
source link: https://www.cnblogs.com/greyzeng/p/16882100.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

设计模式学习(十三):观察者模式

作者:Grey

原文地址:

博客园:设计模式学习(十三):观察者模式

CSDN:设计模式学习(十三):观察者模式

观察者模式#

观察者模式是一种行为型模式。在对象之间定义一个一对多的依赖,当一个对象状态改变的时候,所有依赖的对象都会自动收到通知。

一般可以用做事件处理往往和责任链模式搭配使用, 举个例子:

界面上的按钮上一般都可以绑定事件,当我们按下按钮的时候,可以触发这些事件的执行,这里就可以用观察者模式来做, 我们先定义按钮这个对象

public class Button {
    private List<ActionListener> listeners = new ArrayList<>();

    public void addActionListener(ActionListener listener) {
        this.listeners.add(listener);
    }

    @Override
    public String toString() {
        return "Button{" + "listeners=" + listeners + '}';
    }

    public void buttonPressed() {
        ActionEvent event = new ActionEvent(System.currentTimeMillis(), this);
        listeners.forEach(item -> item.actionPerformed(event));
    }
}

由上可知,Button 中持有了一个列表,这个列表里面装的就是所有事件的列表,我们可以把事件绑定到这个按钮的事件列表中,这样就可以实现按钮执行 press 操作的时候,把对应的事件触发执行了

public interface ActionListener {
    void actionPerformed(ActionEvent event);
}

模拟两个监听事件

public class Listener1 implements ActionListener {
    @Override
    public void actionPerformed(ActionEvent event) {
        System.out.println("Listener 1 listened it source: [" + event.getSource() + "], when is [" + event.getWhen() + "]");
    }
}
public class Listener2 implements ActionListener {
    @Override
    public void actionPerformed(ActionEvent event) {
        System.out.println("Listener 2 listened it source: [" + event.getSource() + "], when is [" + event.getWhen() + "]");
    }
}

主方法在调用的时候,将按钮绑定上述两个监听事件:

public class Main {
    public static void main(String[] args) {
        Button button = new Button();
        button.addActionListener(new Listener1());
        button.addActionListener(new Listener2());
        button.buttonPressed();
    }
}
button.buttonPressed()

的时候,对应的 listener1 和 listener2 就可以执行了。

上述过程的 UML 图如下

image

观察者模式的应用

UML 和 代码#

UML 图

代码

更多#

设计模式学习专栏

参考资料#


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK