java设计模式--观察者模式
观察者模式定义了对象之间的一对多依赖,这样一来,当一个对象改变状态时,它的所有依赖者都会收到通知并自动更新
参考连接 https://www.cnblogs.com/luohanguo/p/7825656.html
一.我们先不用java为观察者模式提供的内置支持
1.创建主题接口
public interface Subject {
//注册成为观察者
public void registerObserver(Observer o);
//移除观察者
public void removeObserver(Observer o);
//当主题改变时,通知观察者
public void notifyObserver();
}
2.创建观察者接口
public interface Observer {
//所有的观察者都必须实现update方法,以实现观察者接口
//当msg改变时,主题会把这些值传给观察者
public void update(String msg);
}
3.创建展示接口
public interface Display {
//显示接口
public void display();
}
4.实现主题
public class SendMsg implements Subject {
private ArrayList observers;
private String msg;
public SendMsg() {
observers = new ArrayList();
}
@Override
public void registerObserver(Observer o) {
//当注册为观察者时,我们只需要把他加进去
observers.add(o);
}
@Override
public void removeObserver(Observer o) {
int i = observers.indexOf(o);
if (i >= 0) {
observers.remove(i);
}
}
@Override
public void notifyObserver() {
for (int i = 0; i < observers.size(); i++) {
Observer observer = (Observer) observers.get(i);
observer.update(msg);
}
}
public void msgChanged(){
notifyObserver();
}
public void setMsg(String msg) {
this.msg = msg;
msgChanged();
}
}
5.实现观察者
public class ReceiveMsg implements Observer,Display{
private String msg;
private Subject sendMsg;
private String receiver;
public ReceiveMsg(String receiver){
this.receiver = receiver;
}
@Override
public void display() {
System.out.print(receiver + "收到消息:"+ msg);
}
@Override
public void update(String msg) {
this.msg = msg;
display();
}
}
6.测试程序
public class Client {
public static void main(String[] args){
SendMsg sendMsg = new SendMsg();
ReceiveMsg receiveMsg = new ReceiveMsg("A");
ReceiveMsg receiveMsgB = new ReceiveMsg("B");
sendMsg.registerObserver(receiveMsg);
sendMsg.registerObserver(receiveMsgB);
sendMsg.setMsg("周一八点开会");
}
}
二.利用java内置对象