标签:观察者模式 abs void server ima lin ini lock over
ISubject
AbstractSubject
SubjectA
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
标签:观察者模式 abs void server ima lin ini lock over
原文地址:http://www.cnblogs.com/cici20166/p/6341431.html