Java设计模式(9)——观察者模式

一、观察者模式定义

  • Observer模式是行为模式之一,它的作用是当一个对象的状态发生变化时,能够自动通知其他关联对象,自动刷新对象状态。
  • Observer模式提供给关联对象一种同步通信的手段,使某个对象与依赖它的其他对象之间保持状态同步。

二、观察者模式的结构

  • Subject(被观察者):被观察的对象。当需要被观察的状态发生变化时,需要通知队列中所有观察者对象。Subject需要维持(添加,删除,通知)一个观察者对象的队列列表。
  • ConcreteSubject:被观察者的具体实现。包含一些基本的属性状态及其他操作。
  • Observer(观察者):接口或抽象类。当Subject的状态发生变化时,Observer对象将通过一个callback函数得到通知。

  • ConcreteObserver: 观察者的具体实现。得到通知后将完成一些具体的业务逻辑处理。

三、观察者模式的特点

  • 侦听事件驱动程序设计中的外部事件
  • 侦听/监视某个对象的状态变化
  • 发布者/订阅者(publisher/subscriber)模型中,当一个外部事件(新的产品,消息的出现等等)被触发时,通知邮件列表中的订阅者

四、观察者模式的缺点

待整理

五、Demo

被观察者

/**
* @description:
* @auther: yangsj
* @created: 2019/3/21 17:25
*/
public class Blog extends Observable {

public void publishArtical(){
Artical artical = new Artical();
artical.setTitle("title");
artical.setCoutent("countent");
this.setChanged();
this.notifyObservers(artical);
}
}

观察者


/**
* @description:
* @auther: yangsj
* @created: 2019/3/21 17:28
*/
public class User implements Observer {
@Override
public void update(Observable o, Object arg) {
Artical artical = (Artical)arg;
System.out.println("title"+artical.getTitle() + " countent" + artical.getCoutent());
}
}

消息基类

package com.nchu.observer;

/**
* @description:
* @auther: yangsj
* @created: 2019/3/21 17:24
*/
public class Artical {
public String title;

public String coutent;

public String getTitle() {
return title;
}

public void setTitle(String title) {
this.title = title;
}

public String getCoutent() {
return coutent;
}

public void setCoutent(String coutent) {
this.coutent = coutent;
}
}

客户端调用

/**
* @description:
* @auther: yangsj
* @created: 2019/3/21 17:30
*/
public class APP {
@Test
public void Test(){
Blog blog = new Blog();
blog.addObserver(new User());
blog.publishArtical();
}
}

六、UML类图

 

posted @ 2019-03-21 19:01  Wayfo  阅读(431)  评论(0编辑  收藏  举报