package lyj.main;
public class App {
public static void main(String[] args) {
Subject subject=new Subject(); //广播接收器,观察者,订阅者 A a=new A(subject); B b=new B(subject); subject.setState(9); subject.setState(999); }}
package lyj.main;
import java.util.ArrayList;/**
* 主题 * @author Administrator * */public class Subject {//状态
private int state; public void setState(int state){ this.state=state; notifiyobserver(); } public int getState(){return state;} //所有的观察者 private ArrayList<Observer> observers=new ArrayList<>(); /** * 订阅 */ public void attach(Observer observer){ observers.add(observer); } /** * 注销 */ public void deattach(Observer observer){ observers.remove(observer); } /** * 通知所有观察者 */ public void notifiyobserver(){ for(Observer observer:observers){ observer.updata(); } }}
package lyj.main;
/** * 观察者,当主题改变的时候,得到视图的最新状态(视图) * @author Administrator * */public abstract class Observer {
//观察的主题
Subject subject; /** * 父类订阅主题 * @param subject */ public Observer(Subject subject) { // TODO Auto-generated constructor stub this.subject=subject; subject.attach(this); } /** * 状态改变 */ public abstract void updata();}
package lyj.main;
public class A extends Observer{
public A(Subject subject) {
super(subject); }@Override
public void updata() { System.out.println("A"+subject.getState()); }}
package lyj.main;
public class B extends Observer{
public B(Subject subject) {
super(subject); }@Override
public void updata() { // TODO Auto-generated method stub System.out.println("B"+subject.getState()); }}