设计模式系列10-观察者模式

观察者模式(Observer Pattern)定义了对象之间的一对多依赖,让多个观察者对象同 时监听一个主体对象,当主体对象发生变化时,它的所有依赖者(观察者)都会收到通 知并更新,属于行为型模式。观察者模式有时也叫做发布订阅模式。观察者模式主要用 于在关联行为之间建立一套触发机制的场景

应用场景

观察者模式在现实生活应用也非常广泛, 比如:微信朋友圈动态通知、消息通知、邮件通知、广播通知

实现方式

JDK

案例: 知识星球上有教师,当有问题提出时,所有教师都能收到这个问题. 论坛作为被观察者, 继承 Observable

论坛

public class Forum extends Observable{

    private String name = "知识星球";
    private static Forum forum = null;
    private Forum(){}

    public static Forum getInstance(){
        if(null == forum){
            forum = new Forum();
        }
        return forum;
    }

    public String getName() {
        return name;
    }

    public void publishQuestion(Question question){
        System.out.println(question.getUserName() + "在" + this.name + "上提交了一个问题。");
        setChanged();
        notifyObservers(question);
    }
}

问题

public class Question {

    private String userName;
    private String content;

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }
}

教师

教师作为观察者 实现 Observer 接口

public class Teacher implements Observer {
    private String name;
    public Teacher(String name){
        this.name = name;
    }

    public void update(Observable o, Object arg) {
        Forum forum = (Forum)o;
        Question question = (Question)arg;
        System.out.println("===============================");
        System.out.println(name + "老师,你好!\n" +
        "您收到了一个来自“" + forum.getName() + "”的提问,希望您解答,问题内容如下:\n" +
        question.getContent() + "\n" +
        "提问者:" + question.getUserName());
    }
}

测试

public static void main(String[] args) {

        Forum forum = Forum.getInstance();
        Teacher tom = new Teacher("Tom");
        Teacher mic = new Teacher("Mic");

        Question question = new Question();
        question.setUserName("小明");
        question.setContent("观察者设计模式适用于哪些场景?");
        forum.addObserver(tom);
        forum.addObserver(mic);
        forum.publishQuestion(question);

    }

自定义实现

案例: 监听鼠标的事件

监听器

public class EventLisenter {

    //JDK底层的Lisenter通常也是这样来设计的
    protected Map<String,Event> events = new HashMap<String,Event>();

    //事件名称和一个目标对象来触发事件
    public void addLisenter(String eventType,Object target){
        try {
            this.addLisenter(
                    eventType,
                    target,
                    target.getClass().getMethod("on" + toUpperFirstCase(eventType),Event.class));
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    public void addLisenter(String eventType,Object target,Method callback){
        //注册事件
        events.put(eventType, new Event(target, callback));
    }


    //触发,只要有动作就触发
    private void trigger(Event event) {
        event.setSource(this);
        event.setTime(System.currentTimeMillis());

        try {
            //发起回调
            if(event.getCallback() != null){
                //用反射调用它的回调函数
                event.getCallback().invoke(event.getTarget(),event);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //事件名称触发
    protected void trigger(String trigger){
        if(!this.events.containsKey(trigger)){return;}
        trigger(this.events.get(trigger).setTrigger(trigger));
    }

    //逻辑处理的私有方法,首字母大写
    private String toUpperFirstCase(String str){
        char[] chars = str.toCharArray();
        chars[0] -= 32;
        return String.valueOf(chars);
    }

}

标准事件Event

public class Event {
    //事件源,事件是由谁发起的保存起来
    private Object source;
    //事件触发,要通知谁
    private Object target;
    //事件触发,要做什么动作,回调
    private Method callback;
    //事件的名称,触发的是什么事件
    private String trigger;
    //事件触发的时间
    private long time;

    public Event(Object target, Method callback) {
        this.target = target;
        this.callback = callback;
    }

    public Event setSource(Object source) {
        this.source = source;
        return this;
    }

    public Event setTime(long time) {
        this.time = time;
        return this;
    }

    public Object getSource() {
        return source;
    }

    public Event setTrigger(String trigger) {
        this.trigger = trigger;
        return this;
    }

    public long getTime() {
        return time;
    }

    public Object getTarget() {
        return target;
    }

    public Method getCallback() {
        return callback;
    }

    @Override
    public String toString() {
        return "Event{" + "\n" +
                "\tsource=" + source.getClass() + ",\n" +
                "\ttarget=" + target.getClass() + ",\n" +
                "\tcallback=" + callback + ",\n" +
                "\ttrigger='" + trigger + "',\n" +
                "\ttime=" + time + "'\n" +
                '}';
    }
}

鼠标回调事件

public class MouseEventCallback {

    public void onClick(Event e){
        System.out.println("===========触发鼠标单击事件==========" + "\n" + e);
    }

}

鼠标对象

public class Mouse extends EventLisenter {

    public void click(){
        System.out.println("调用单击方法");
        this.trigger(MouseEventType.ON_CLICK);
    }

}

事件枚举

public interface MouseEventType {
    //单击
    String ON_CLICK = "click";
}

测试

public static void main(String[] args) {
        MouseEventCallback callback = new MouseEventCallback();
        Mouse mouse = new Mouse();
        mouse.addLisenter(MouseEventType.ON_CLICK,callback);
        mouse.click();
    }

Guava

基于Guava可以轻松落地观察者模式.

事件

public class GuavaEvent {

    @Subscribe
    public void subscribe(String str){
        System.out.println("执行subscribe方法,传入的参数是:" + str);
    }

}

通知

public static void main(String[] args) {
        //消息总线
        EventBus eventBus = new EventBus();
        GuavaEvent guavaEvent = new GuavaEvent();
        eventBus.register(guavaEvent);
        eventBus.post("Tom");
    }

源码体现

来看一下 Spring 中的 ContextLoaderListener 实现了 ServletContextListener 接口, ServletContextListener 接口又继承了 EventListener,在 JDK 中 EventListener 有非常 广泛的应用.
image

public class ContextLoaderListener extends ContextLoader implements ServletContextListener {
    public ContextLoaderListener() {
    }

    public ContextLoaderListener(WebApplicationContext context) {
        super(context);
    }

    public void contextInitialized(ServletContextEvent event) {
        this.initWebApplicationContext(event.getServletContext());
    }

    public void contextDestroyed(ServletContextEvent event) {
        this.closeWebApplicationContext(event.getServletContext());
        ContextCleanupListener.cleanupAttributes(event.getServletContext());
    }
}

观察者模式的优缺点

  • 优点:
  1. 观察者和被观察者之间建立了一个抽象的耦合。
  2. 观察者模式支持广播通信。
  • 缺点:
  1. 观察者之间有过多的细节依赖、提高时间消耗及程序的复杂度。
  2. 使用要得当,要避免循环调用。
posted @ 2021-09-27 20:43  狻猊的主人  阅读(54)  评论(0编辑  收藏  举报