先看一下类图:
具体实现:
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); } }
时间: 2024-10-03 23:10:26