观察者模式
观察者模式,应以一种一对多的依赖关系,当状态改变,自动通知其他依赖的对象。也就是发布订阅模式。
具体实现包括四个部分:
- 抽象被观察者;
- 被观察者角色;
- 抽象观察者;
- 观察者角色。
创建抽象观察者:
1 public interface Observer { 2 3 void update(String msg); 4 5 String getName(); 6 }
创建抽象被观察者:
1 public interface Subject { 2 3 void attach(Observer observer); 4 5 void detach(Observer Observer); 6 7 void notifyObservers(String msg); 8 }
创建两个观察者:
1 public class LancerObserver implements Observer { 2 3 private String name; 4 5 public LancerObserver(String name) { 6 this.name = name; 7 } 8 9 @Override 10 public String getName() { 11 return name; 12 } 13 14 @Override 15 public void update(String msg) { 16 System.out.println(name + " got msg " + msg); 17 } 18 } 19 20 public class SaberObserver implements Observer { 21 22 private String name; 23 24 public SaberObserver(String name) { 25 this.name = name; 26 } 27 28 @Override 29 public void update(String msg) { 30 System.out.println(name + " got msg " + msg); 31 } 32 33 @Override 34 public String getName() { 35 return name; 36 } 37 }
创建被观察者:
1 public class SanGrealSubject implements Subject { 2 3 List<Observer> observers = new ArrayList<>(10); 4 5 @Override 6 public void attach(Observer observer) { 7 observers.add(observer); 8 } 9 10 @Override 11 public void detach(Observer target) { 12 observers.removeIf(observer -> StringUtils.equalsIgnoreCase(observer.getName(), target.getName())); 13 } 14 15 @Override 16 public void notifyObservers(String msg) { 17 for (Observer observer : observers) { 18 observer.update(msg); 19 } 20 } 21 }
创建测试方法:
1 public class Main { 2 3 public static void main(String[] args) { 4 Subject subject = new SanGrealSubject(); 5 6 Observer saber = new SaberObserver("Arthur"); 7 Observer lancer = new LancerObserver("CuChulainn"); 8 9 subject.attach(saber); 10 subject.attach(lancer); 11 subject.notifyObservers("i am CuChulainn"); 12 13 subject.detach(lancer); 14 subject.notifyObservers("why"); 15 } 16 }