Java学习笔记——设计模式之十.观察者模式
Posted Tomas曼
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Java学习笔记——设计模式之十.观察者模式相关的知识,希望对你有一定的参考价值。
观察者模式(Observer),定义了一种一对多的依赖关系,让多个观察者对象同时监听某一个主题对象。这个主题对象在状态发生变化时,会通知所有观察者对象,使他们能够自动更新自己。
Subject类:
1 package cn.happy.design_pattern._10publishsubscribe; 2 3 import java.util.ArrayList; 4 import java.util.List; 5 6 public class Subject { 7 8 private List<Observer> observers = new ArrayList<>(); 9 10 public void attach(Observer observer){ 11 observers.add(observer); 12 } 13 14 public void detach(Observer observer){ 15 observers.remove(observer); 16 } 17 18 public void mNotify(){ 19 for (Observer item : observers) { 20 item.update(); 21 } 22 } 23 }
Observer类:
1 package cn.happy.design_pattern._10publishsubscribe; 2 3 public abstract class Observer { 4 5 public abstract void update(); 6 }
ConcreteSubject类:
1 package cn.happy.design_pattern._10publishsubscribe; 2 3 public class ConcreteSubject extends Subject { 4 5 private String subjectState; 6 7 String getSubjectState() { 8 return subjectState; 9 } 10 11 void setSubjectState(String subjectState) { 12 this.subjectState = subjectState; 13 } 14 15 }
ConcreteObserver类:
1 package cn.happy.design_pattern._10publishsubscribe; 2 3 public class ConcreteObserver extends Observer { 4 5 private String name; 6 private String observerState; 7 private ConcreteSubject subject; 8 9 public ConcreteObserver(ConcreteSubject subject, String name) { 10 this.subject = subject; 11 this.name = name; 12 } 13 14 @Override 15 public void update() { 16 observerState = subject.getSubjectState(); 17 System.out.println("观察者"+name+"的新状态是"+observerState); 18 } 19 //省略getter and setter 20 }
测试类:
1 package cn.happy.design_pattern._10publishsubscribe; 2 3 public class Mmain { 4 5 public static void main(String[] args) { 6 ConcreteSubject subject = new ConcreteSubject(); 7 subject.attach(new ConcreteObserver(subject, "X")); 8 subject.attach(new ConcreteObserver(subject, "Y")); 9 subject.attach(new ConcreteObserver(subject, "Z")); 10 subject.setSubjectState("ABC"); 11 subject.mNotify(); 12 } 13 14 }
以上是关于Java学习笔记——设计模式之十.观察者模式的主要内容,如果未能解决你的问题,请参考以下文章