观察者模式
观察者模式
一个对象状态改变,可以引起多个对象的状态改变
Subject 抽象主题
Observer 抽象观察者
Boiler 具体主题
LED 具体观察者
Client 测试例子
package com.moreas.design; import java.util.ArrayList; import java.util.List; public abstract class Subject{ private List<Observer> observers = new ArrayList<Observer>(); //添加观察者 public void attach(Observer observer) { observers.add(observer); } //移除观察者 public void tach(Observer observer) { observers.remove(observer); } //通知所有的被观察者 public void notice(Subject subject){ for (Observer obj: observers) { obj.update(subject); } } }
package com.moreas.design; public abstract class Observer { public abstract void update(Subject subject); }
package com.moreas.design; public class Boiler extends Subject { //水温 public int temperature; /**烧水*/ public void onBoil(){ for(int i=0;temperature<100;i++){ temperature=temperature+1; //升温 super.notice(this); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } } }
package com.moreas.design; public class LED extends Observer { @Override public void update(Subject subject) { Boiler boiler = (Boiler) subject; System.out.println("当前水温:" + boiler.temperature); } }
package com.moreas.design; public class Client { public static void main(String[] args) { //观察者 // Observer alarm=new Alarm(); Observer led=new LED(); //主题 Boiler boiler=new Boiler(); // boiler.attach(alarm); boiler.attach(led); //烧水 boiler.onBoil(); } }
观察者模式,简单改动
public class Subject { private List<Observer> observers = new ArrayList<>(); private int state; public int getState() { return this.state; } public void setState(int state) { if (state == this.state) { return; } this.state = state; notifyAllObserver(); } public void attach(Observer observer) { observers.add(observer); } private void notifyAllObserver() { observers.stream().forEach(x -> x.update()); } }
public abstract class Observer { protected Subject subject; public Observer(Subject subject) { this.subject = subject; this.subject.attach(this); } public abstract void update(); }
public class BinaryObserver extends Observer { public BinaryObserver(Subject subject) { super(subject); } @Override public void update() { System.out.println("Binary String:" + Integer.toBinaryString(subject.getState())); } }
//Octal 八进制 public class OctalObserver extends Observer { public OctalObserver(Subject subject) { super(subject); } @Override public void update() { System.out.println("Octal String:" + Integer.toOctalString(subject.getState())); } }
public class Client { public static void main(String[] args) { final Subject subject = new Subject(); new BinaryObserver(subject); new OctalObserver(subject); System.out.println("=================="); subject.setState(10); System.out.println("=================="); subject.setState(10); System.out.println("=================="); subject.setState(15); } }