观察者模式:
设计到的角色:
主题:是一个接口,同时必须包含一个观察者列表,必须有添加,删除,通知观察者的方法
具体主题:主题的实现类
观察者:也是接口,接口中需要定义接到通知之后的操作
具体观察者:观察者的实现类,同时观察者要订阅主题则需要注册,即必须要添加到主题的观察者列表中,取消订阅则是删除
当主题的状态发生变化的时候,所有的观察者都得到通知
主题:
package com.design2;
public interface SubjectInterface {
void add(ObserverInterface observer);
void delete(ObserverInterface observer);
void notifyObserver();
void giveMess(String mess);
}
具体主题:
package com.design2;
import java.util.ArrayList;
import java.util.List;
public class Subject implements SubjectInterface {
List<ObserverInterface> observerList;
String mess;
boolean isNotify;
public Subject(){
observerList = new ArrayList<ObserverInterface>();
mess = "";
isNotify = false;
}
@Override
public void add(ObserverInterface observer) {
if (observer != null && !observerList.contains(observer)) {
observerList.add(observer);
}
}
@Override
public void delete(ObserverInterface observer) {
if (observerList.contains(observer)) {
observerList.remove(observer);
}
}
@Override
public void notifyObserver() {
if (isNotify) {
for (ObserverInterface object : observerList) {
object.update(mess);
}
}
}
@Override
public void giveMess(String message) {
if (mess.equals(message)) {
isNotify = false;
} else {
mess = message;
isNotify = true;
}
}
}
观察者接口:
package com.design2;
public interface ObserverInterface {
void update(String mess);
}
观察者:
package com.design2;
public class Observer implements ObserverInterface {
private String name;
private SubjectInterface subject;
public Observer(String name,SubjectInterface subject){
this.name = name;
subject.add(this);
}
@Override
public void update(String mess) {
System.out.println(name + "接受的消息:" + mess);
}
}
测试:
package com.design2;
public class Application {
public static void main(String[] args) {
SubjectInterface subject = new Subject();
ObserverInterface zhangsan = new Observer("zhangsan", subject);
ObserverInterface lisi = new Observer("zhangsan", subject);
subject.giveMess("123");
subject.notifyObserver();
subject.giveMess("123");
subject.notifyObserver();
subject.giveMess("456");
subject.notifyObserver();
}
}
原文地址:https://www.cnblogs.com/xiaokang-share/p/9270909.html