Observer: 观察者模式

Intent:
"Define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically."
Use case:
While any customer enter into system :
* send a welcome email
* verify the customer's address.
UML Diagram:
Code:
package com.jim.observer; import java.util.Enumeration; import java.util.Vector; class Customer { static private Vector<Observer> myObs; static { myObs = new Vector<Observer>(); //ObserverCellection } private String id; public String getId() { return id; } public Customer(String id) { this.id = id; } public static void reg(Observer o) { myObs.addElement(o); } public static void unreg(Observer o) { myObs.remove(o); } //notify all observers public void notifyObs() { for (Enumeration<Observer> e = myObs.elements(); e.hasMoreElements();) { ((Observer) e.nextElement()).update(this); } } } abstract class Observer { public Observer() { Customer.reg(this); //register observer } abstract public void update(Customer myCust); } class WelcomeLetter extends Observer { public WelcomeLetter() { super(); } public void update(Customer myCust) { System.out.println("has sent welcome email to " + myCust.getId()); } } class AddrVerify extends Observer { public AddrVerify() { super(); } public void update(Customer myCust) { System.out.println("has verifed address of " + myCust.getId()); } } public class ObTest { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub Customer cust1 = new Customer("cust1"); Customer cust2 = new Customer("cust2"); Observer wel = new WelcomeLetter(); Observer add = new AddrVerify(); cust1.notifyObs(); cust2.notifyObs(); } }

Output:
has sent welcome email to cust1
has verifed address of cust1
has sent welcome email to cust2
has verifed address of cust2
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值