朝花夕拾--观察者模式-java笔记
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了朝花夕拾--观察者模式-java笔记相关的知识,希望对你有一定的参考价值。
先看一下类图:
具体实现:
package obs.self; /** * 被观察对象 * @author wangfeihu * */ public interface Subject { /** * 增加一个观察者 * @param observer */ public void addObserver(Observer observer); public void removeObserver(Observer observer); /** * 通知所有观察者 * @param msg */ public void notifyObservers(Object msg); }
package obs.self; /** * 观察者 * @author wangfeihu * */ public interface Observer { public void update(Object msg); }
package obs.self; import java.util.HashSet; import java.util.Set; /** * 银行账户, 余额发生变化的时候进行相关的通知 * @author wangfeihu * */ public class Account implements Subject { private int balance = 0; public Set<Observer> obervers = new HashSet<Observer>(); public void addObserver(Observer observer) { obervers.add(observer); } public void removeObserver(Observer observer) { obervers.remove(observer); } public void notifyObservers(Object msg) { for (Observer obs : obervers) { obs.update(msg); } } public int getBalance() { return balance; } public void setBalance(int balance) { this.balance = balance; this.notifyObservers("账户余额发生改变," + balance); } /** * 取款 * @param money */ public void withdraw(int money) { this.setBalance(this.balance - money); } /** * 存款 * @param money */ public void deposit(int money) { this.setBalance(this.balance + money); } }
package obs.self; public class MobileObserver implements Observer { public void update(Object msg) { System.out.println("手机短信提醒:" + msg); } }
package obs.self; public class WechatObserver implements Observer { public void update(Object msg) { System.out.println("微信服务号提醒:" + msg); } }
执行:
package obs.self; public class ObserverTest { public static void main(String[] args) { Account accountSubject = new Account(); MobileObserver mobileObserver = new MobileObserver(); WechatObserver wechatObserver = new WechatObserver(); accountSubject.addObserver(mobileObserver); accountSubject.addObserver(wechatObserver); // 存钱 accountSubject.deposit(10000); // 取钱 accountSubject.withdraw(500); //移除短信通知 accountSubject.removeObserver(mobileObserver); accountSubject.withdraw(600); } }
本文出自 “流浪的脚步” 博客,请务必保留此出处http://now51jq.blog.51cto.com/3474143/1875450
以上是关于朝花夕拾--观察者模式-java笔记的主要内容,如果未能解决你的问题,请参考以下文章