标签:客户端 玩家 模型 protect 个人 style print 监听器 sub()
观察者模式Observer
广播机制
场景:多个观察者--被通知改变
CS的时候,人物移动坐标变化,更新每个人地图上的坐标
核心:当目标对象(Subject)的状态值改变时,需要及时告知所有观察者(Observer),使他们做出响应
开发中常见的场景:
-聊天室程序中,服务器转发给所有客户端
-网络游戏(多人联机)中,服务器将各个玩家的状态分发
-邮件订阅
-Servlet中,监听机制
-Android中的广播机制
-JDK的AWT中事件处理模型,基于观察者模式的委派事件模型(Delegation Event Model)(事件源------目标对象,事件监听器------观察者)
-京东商城中,群发商品打折信息
public class Subject {
//被观察者队伍
protected List<Observer> observers=new ArrayList<>();
public void addObserver(Observer obs) {
observers.add(obs);
}
public void removeObserver(Observer obs) {
observers.remove(obs);
}
//通知所有被观察者的状态更新
public void notifyAllObserve() {
for(Observer obs:observers) {
obs.update();
}
}
}
class ConcreteSub extends Subject{
private int state;
public int getState() {
return state;
}
public void setState(int state) {
this.state = state;
this.notifyAllObserve();
}
}
public interface Observer {
void update();
}
class ObserverA implements Observer{
private int myState;
private Subject sub;
public ObserverA(Subject sub) {
this.sub = sub;
}
@Override
public void update() {
myState=((ConcreteSub)sub).getState();
System.out.println("状态已更新");
}
}
public class Client {
public static void main(String[] args) {
ConcreteSub sub=new ConcreteSub();
ObserverA obs1=new ObserverA(sub);
ObserverA obs2=new ObserverA(sub);
ObserverA obs3=new ObserverA(sub);
//添加到被观察者队伍
sub.addObserver(obs1);
sub.addObserver(obs2);
sub.addObserver(obs3);
sub.setState(1000);
}
}
#####################################手动分隔符##############################################
java.util.Observable(相当于上面定义的Subject类)和java.util.Observer(相当于上面定义的Observer接口)
public class ConcreteSubject extends Observable{
private int state;
public void set(int s) {
state=s;
setChanged();
this.notifyObservers();
}
public int getState() {
return state;
}
public void setState(int state) {
this.state = state;
}
}
public class ObserverA implements Observer{
private int myState;
@Override
public void update(Observable o, Object arg) {
myState=((ConcreteSubject)o).getState();
}
public int getMyState() {
return myState;
}
public void setMyState(int myState) {
this.myState = myState;
}
}
public class Client {
public static void main(String[] args) {
ConcreteSubject cs=new ConcreteSubject();
ObserverA obs1=new ObserverA();
ObserverA obs2=new ObserverA();
ObserverA obs3=new ObserverA();
//添加至队伍中
cs.addObserver(obs1);
cs.addObserver(obs2);
cs.addObserver(obs3);
cs.set(100);
System.out.println(obs1.getMyState());
System.out.println(obs2.getMyState());
System.out.println(obs2.getMyState());
}
}
设计模式之GOF23观察者模式
标签:客户端 玩家 模型 protect 个人 style print 监听器 sub()
原文地址:https://www.cnblogs.com/code-fun/p/11366508.html