Observer && being observed, e.g. ProductList && e-commerce companies.

Reason to adopt this model: de-coupling.

Java中的观察者模式要同时存在观察者和被观察者,观察者可以是多个。

被观察者需要继承java.util.Observerable类. E.g. ProductList:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
public class ProductList extends Observable {
private List<String> productList = null;
private static ProductList instance; // only one
private ProductList() {} // singleton

/* singleton:
1. private constructor
2. getInstance() method to create the only object
3. "new" inside getInstance()

@return the only ProductList instance
*/
public static ProductList getInstance() {
if (instance == null) {
instance = new ProductList();
instance.productList = new ArrayList<String>();
}
return instance;
}

/*
Add observer (e-commerce interface)
*/
public void addProductListObserver(Observer observer) {
this.addObserver(observer);
}

/*
add product
*/
public void addProduct(String newProduct) {
productList.add(newProduct);
System.out.println("productList add:" + newProduct);
this.setChanged(); // observerd changed
this.notifyObservers(newProduct); // notify observers, add new products
}
}

观察者需要实现java.util.Observer接口的update方法:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public class JDObserver implements Observer {
@Override
public void update(Observerable o, Object product) {
String newProduct = (String) product;
System.err.println("发送新产品" + newProduct + "同步到京东商城");
}
}

public class TBObserver implements Observer {
@Override
public void update(Observerable o, Object product) {
String newProduct = (String) product;
System.err.println("发送新产品" + newProduct + "同步到淘宝");
}
}

main:

1
2
3
4
5
6
7
8
public static void main(String[] args) {
ProductList observable = ProductList.getInstance(); // singleton new object
TBObserver tbObserver = new TBObserver();
JDObserver jdObserver = new JDObserver();
observable.addObserver(jdObserver);
observable.addObserver(tbObserver);
observable.addProduct("新增产品1");
}

output:

1
2


(TO BE MODIFIED)