发布订阅模式使用

    最近早上地铁上一直看设计模式,代码中却使用不上,今天恰好碰到一个新需求,感觉和发布订阅模式有点相同,借用了一下理念,虽然代码写的很烂,但是还是第一次去试着用设计模式,记录一下成长的第一步。

    需求大概是,往前端推送数据的时候,因为涉及到整个北京市的数据和北京市各个地区的数据,当前端不给我发送请求的时候,我这边是正常推整个北京市新增的数据,而当前端给我发送请求的时候,会带着某个区的行政编码,这时候我发送整个北京市数据就要停止,转而给推送这个区的数据,而当前端发请求通知我改为整个北京市数据的时候,再次改变,我把前端的请求当做通知者,根据请求的不同改变查阅的状态,把我的推送当做订阅者,根据发布者查阅状态的变化,推送不同的数据。

  通知者代码如下

@RestController
@RequestMapping("/api/notify")
public class ZoneSubject {

    @Resource(name = "zoneObserver")
    private Observer observer;

    private Boolean state;

    private Integer zone;
    
    public void Notify(){

            observer.update();
    }
    
    @RequestMapping("/city")
    public  void updateState(){
        this.state=true;
        this.Notify();
    }

    @RequestMapping("/area/{zone}")
    public  void getTip(@PathVariable Integer zone){
        this.state=false;
        this.zone=zone;
        this.Notify();
    }

观察者代码如下

@Component(value = "zoneObserver")
public class ZoneObserver extends  Observer{

    @Resource
    private ZoneSubject zoneSubject;


    @Resource(name = "alarmToTVService")
    private AlarmToTVService alarmToTVService;

    private Boolean state=false;

    private Integer zone=110000;

    @Override
    public void update() {
        this.state=zoneSubject.getState();
        this.zone=zoneSubject.getZone();
    }


    public void  sendTip(String type){
        if(type.equals("0")){
            alarmToTVService.sendTipFocusToTV(type);
        }else {
            if (state) {
                alarmToTVService.sendTipFocusToTV(type);
            } else {
                alarmToTVService.sendTipFocus(type, zone);
            }
        }
    }
}

其余地方调用观察者的sendTip()方法时,就会给推送对应的数据了。

猜你喜欢

转载自www.cnblogs.com/wxw7blog/p/9585797.html
今日推荐