温故知新
首先我们定义两个接口:一个是观察者有一个方法 updata();接收被观察者改变后发送过来的消息,另一个是观察者 有三个方法
添加观察者1、addWather(Watcher watcher)
删除观察者2、 removeWather(Watcher wather)
给观察者发送消息3、notify(String str)
观察者接口:
package Interface;
/**
* 观察者接口
* @author hu
*
*/
public interface Watcher {
public void updata(String str);
}
被观察者接口:
package Interface;
/**
* 被观察者接口
* @author hu
*
*/
public interface Watchered {
public void addWatcher(Watcher watcher);
public void removeWatcher(Watcher watcher);
public void notifyWatcher(String str);
}
观察者类:
package founction;
import Interface.Watcher;
public class CreaterWatcher implements Watcher {
@Override
public void updata(String str) {
System.out.println(str);
}
}
被观察者类:
package founction;
import java.util.ArrayList;
import java.util.List;
import Interface.Watcher;
import Interface.Watchered;
/**
* 被观察者的类
* @author hu
*
*/
public class CreaterWatchered implements Watchered {
List<Watcher> list = new ArrayList<>();
@Override
public void addWatcher(Watcher watcher) {
list.add(watcher);
}
@Override
public void removeWatcher(Watcher watcher) {
list.remove(watcher);
}
@Override
public void notifyWatcher(String str) {
/**
* 方法1: 迭代器循环
*/
/**
* 方法2:增强for
*/
/**
* 方法3:普通for循环
*/
for (int i = 0; i < list.size(); i++) {
list.get(i).updata(str);
}
}
}
测试类:
package Test;
import founction.CreaterWatcher;
import founction.CreaterWatchered;
/**
* 测试类
* @author hu
*
*/
public class TestRxjava {
public static void main(String[] args) {
CreaterWatcher watcher1 = new CreaterWatcher();
CreaterWatcher watcher2 = new CreaterWatcher();
CreaterWatcher watcher3 = new CreaterWatcher();
CreaterWatcher watcher4 = new CreaterWatcher();
CreaterWatchered watchered = new CreaterWatchered();
watchered.addWatcher(watcher1);
watchered.addWatcher(watcher2);
watchered.addWatcher(watcher3);
watchered.addWatcher(watcher4);
watchered.notifyWatcher("我开始偷东西了");
}
}