观察者模式代码
public class One implements Subject {
private ArrayList<Observer> observers = new ArrayList<>();
private String msg;
@Override
public void registerObserver(Observer observer) {
observers.add(observer);
}
@Override
public void removeObserver(Observer observer) {
int index = observers.indexOf(observer);
if (index >= 0) {
observers.remove(index);
}
}
@Override
public void notifyObservers() {
for (Observer observer : observers) {
observer.update(msg);
}
}
/**
* 主题更新信息
*/
public void setMsg(String msg) {
this.msg = msg;
notifyObservers();
}
}
订阅者
package com.example.jingbin.designpattern.observer.classs;
import android.util.Log;
import com.example.jingbin.designpattern.observer.interfaces.Observer;
import com.example.jingbin.designpattern.observer.interfaces.Subject;
/**
* Created by jingbin on 2016/10/21.
* 模拟第一个使用者
*/
public class ObserverUser1 implements Observer {
public ObserverUser1(Subject subject) {
subject.registerObserver(this);
}
@Override
public void update(String msg) {
Log.e("-----ObserverUser1 ", "管道流水面 在线面捞着吃 ");
}
}
用法
// 创建两个订阅者
One one= new One ();
observerUser1 = new ObserverUser1(one);
one.setMsg("发放面条了");
来源:CSDN
作者:蓝色笙箫
链接:https://blog.csdn.net/bxllove/article/details/103602368