写个责任链模式(混用观察者)

来源:互联网 发布:淘宝买到盗版书怎么办 编辑:程序博客网 时间:2024/05/17 09:34

定义:

责任链模式重点在于链上,可以在发生者和处理者之间解耦,使事件在链上传递,直到有一个类处理了这个事件。

在工作中,我们跟观察者模式混用在一起,

处理方法实现对应的接口,在spring中可以加入@Order定义加载顺序


观察者:
@Componentpublic class XEventDispatch implements Observer {    @Autowired    private List<XEventCustomer>xEventCustomers;    public void update(Observable source, Object arg) {        //事件的源头        X x = (X) arg;        //事件        XEvent event = (XEvent) source;//责任链变种        for (XEventCustomer xEventCustomer : xEventCustomers) {            if (xEventCustomer.getStatus().getCode() == event.getType().getCode()) {                xEventCustomer.exec(event);                return;            }        }    }}

被观察者:public class XEvent extends Observable {    private XEventDispatch xEventDispatch;    //事件起源    private X source;    //事件的类型    private PublicClassInfoStatusEnum type;    //传入事件的源头,默认为新建类型    public SmallClassEvent(SmallClass smallClass, SmallClassEventDispatch smallClassEventDispatch) {        this(smallClass, smallClassEventDispatch, PublicClassInfoStatusEnum.CREATE);    }    //事件源头以及事件类型    public XEvent(X p, XEventDispatch xEventDispatch, StatusEnum type) {        this.xeventDispatch = xEventDispatch;        this.source = p;        this.type = type;        //事件触发        this.notifyEventDispatch();    }    //通知事件处理中心    private void notifyEventDispatch() {        super.addObserver(xEventDispatch);        super.setChanged();        super.notifyObservers(source);    }}


原创粉丝点击