原创

JAVA设计模式-观察者模式(Observe)

观察者模式

其实就是一个发布者和订阅者之间的关系

如果订阅者订阅了发布者,那么发布者发布一条消息,订阅者就会立马知道。

中间的关系也就是订阅者需要去订阅消息(也就是,发布者的通知资源池子(也就是存储订阅者的对象集合)里面存在的,当发布者发布对应消息的时候,发布者就会立即调用订阅者里面的集合里面的所有加入到订阅池子的订阅者)

一个简单的观察者模式的示例

Subject(发布者)

package com.example.demo.observe.subject;

import com.example.demo.observe.core.EventListener;

public class Subject extends EventListener {

    //通常的话,采用动态代理来实现监控,避免了代码入侵。
    public void add(){
        System.out.println("调用添加的方法");
        trigger(SubjectEventType.ON_ADD);
    }
    public void remove(){
        System.out.println("调用删除方法");
        trigger(SubjectEventType.ON_REMOVE);
    }
}

Observe(观察者)

package com.example.demo.observe.subject;

import com.example.demo.observe.core.Event;

public class Observe  {
    public void advice(Event e){
        System.out.println("=====触发事件,打印日志=======");
        System.out.println(e);
    }
}

事件类(记录了发布者,订阅者,时间,以及需要通知的方法)

package com.example.demo.observe.core;

import java.lang.reflect.Method;

public class Event {

    //事件源
    private Object source;
    //通知目标
    private Object target;
    //回调
    private Method callable;
    //触发
    private String trigger;
    //事件
    private Long time;

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

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

    public Object getSource() {
        return source;
    }

    public Object getTarget() {
        return target;
    }

    public void setTarget(Object target) {
        this.target = target;
    }

    public Method getCallable() {
        return callable;
    }

    public void setCallable(Method callable) {
        this.callable = callable;
    }

    public String getTrigger() {
        return trigger;
    }

    public Long getTime() {
        return time;
    }

    public void setTime(Long time) {
        this.time = time;
    }

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

    @Override
    public String toString() {
        return "Event{\n" +
                "\tsource=" + source + ",\n" +
                "\tttarget=" + target + ",\n" +
                "\tcallable=" + callable + ",\n" +
                "\ttrigger='" + trigger + '\'' + ",\n" +
                '}';
    }
}

订阅池(也就是记录所有订阅者信息,及操作订阅者的类)

package com.example.demo.observe.core;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

public class EventListener {

    protected Map<Enum, Event> events = new HashMap<>();

    public void addListener(Enum eventType, Object target, Method callback ){
        //注册事件,用反射调用
        events.put(eventType, new Event(target, callback));

    }

    protected void trigger(Enum call) {
        if (!this.events.containsKey(call)) {
            return;
        }
        trigger(this.events.get(call).setTrigger(call.toString()));
    }
    private void trigger(Event e){
        e.setSource(this);
        e.setTime(System.currentTimeMillis());

        try {
            Object invoke = e.getCallable().invoke(e.getTarget(), e);
        } catch (Exception ex) {
            ex.printStackTrace();
        }


    }
}

订阅分类(对应发布者的操作分类)

package com.example.demo.observe.subject;

public enum  SubjectEventType {
    ON_ADD,
    ON_REMOVE,
    ON_EDIT,
    ON_QUERY;
}

测试类

package com.example.demo.observe.subject;

import com.example.demo.observe.core.Event;

import java.lang.reflect.Method;

public class ObserverTest {

    public static void main(String[] args) {
        try {
            //观察者
            Observe observe = new Observe();
            Method advice = observe.getClass().getMethod("advice", new Class<?>[]{Event.class});


            Subject subject = new Subject();
            subject.addListener(SubjectEventType.ON_ADD, observe, advice);
            subject.addListener(SubjectEventType.ON_REMOVE, observe, advice);
            subject.remove();
            subject.add();
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
正文到此结束
本文目录