首页 > 代码库 > 朝花夕拾--观察者模式-java笔记
朝花夕拾--观察者模式-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笔记
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。