观察者(发布订阅)模式_发送状态变化通知给所有关注的对象
/** * @author maikec * @date 2019/5/15 */public abstract class AbstractSubject { protected QueueobserverQueue; /** * 添加观察者 * @param observer */ public final void addObserver(AbstractObserver observer){ if (null == observerQueue){ ReentrantReadWriteLock.WriteLock writeLock = new ReentrantReadWriteLock().writeLock(); try { if (writeLock.tryLock()){ if (null == observerQueue){ observerQueue = new PriorityQueue<>( ); } } }finally { writeLock.unlock(); } } ReentrantReadWriteLock.WriteLock writeLock = new ReentrantReadWriteLock().writeLock(); try { if (writeLock.tryLock()){ observerQueue.add( observer ); } }finally { writeLock.unlock(); } } public final void remove(AbstractObserver observer){ Assert.notNull( observerQueue,"观察者列表未初始化" ); Assert.notNull( observer,"入参不能为null" ); ReentrantReadWriteLock.WriteLock writeLock = new ReentrantReadWriteLock().writeLock(); try { if (writeLock.tryLock()){ observerQueue.remove( observer ); } }finally { writeLock.unlock(); } } public final void notifyObservers(){ observerQueue.forEach( observer -> observer.update( this ) ); } /** * 获取主题状态 * @return */ public abstract String getSubjectStatus();}/** * @author maikec * @date 2019/5/15 */public abstract class AbstractObserver { /** * 观察AbstractSubject状态变化 * @param subject */ protected abstract void update(AbstractSubject subject);}/** * @author maikec * @date 2019/5/15 */public class ConcreteSubject extends AbstractSubject { @Setter private String status; @Override public String getSubjectStatus() { return status; }}/** * @author maikec * @date 2019/5/15 */public class ConcreteObserver extends AbstractObserver { @Override protected void update(AbstractSubject subject) { System.out.println( subject.getSubjectStatus() ); }}** * @author maikec * @date 2019/5/15 */public class ObserverDemo { public static void main(String[] args) { ConcreteSubject concreteSubject = new ConcreteSubject(); concreteSubject.setStatus( "Active" ); concreteSubject.addObserver( new ConcreteObserver() ); concreteSubject.notifyObservers(); concreteSubject.setStatus( "Down" ); concreteSubject.notifyObservers(); }}复制代码
附录
个人GitHub设计模式案例
声明
引用该文档请注明出处