观察者模式
Posted ~~Cc
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了观察者模式相关的知识,希望对你有一定的参考价值。
ISubject
View Code
AbstractSubject
View Code
SubjectA
View Code
IObserver
package Observer; public interface IObserver { void update(String changeMsg); }
ObserverA
package Observer; public class ObserverA implements IObserver{ @Override public void update(String changeMsg) { System.out.println("observerA recieves the information:" + changeMsg); } }
ObserverB
package Observer; public class ObserverB implements IObserver{ @Override public void update(String changeMsg) { System.out.println("observerB recieves the information:" + changeMsg); } }
ObserverC
package Observer; public class ObserverC implements IObserver{ @Override public void update(String changeMsg) { System.out.println("observerC recieved the information:" + changeMsg); } }
Test.java
public static void main(String[] args) { SubjectA sA = new SubjectA(); sA.addObserver(new ObserverA()); sA.addObserver(new ObserverB()); sA.addObserver(new ObserverC()); sA.inform("change my name to cc!"); }
运行结果
JDK已经实现了一套观察者模式,可以直接复用相关代码,主要业务逻辑会被封装在Observer的update方法中。
subject类:java.util.Observable
observer类:java.util.Observer
以上是关于观察者模式的主要内容,如果未能解决你的问题,请参考以下文章
Java设计模式补充:回调模式事件监听器模式观察者模式(转)