ProductList.class
package com.proxy.cn.Design_patterns.Observer_mode;
import java.util.ArrayList;
import java.util.List;
import java.util.Observable;
import java.util.Observer;
public class ProductList extends Observable {
private List<String> productList = null;//产品列表
private static ProductList instance;//类唯一实例
private ProductList(){}//构造器私有化
/**
* 获取唯一实例
* @return 产品列表唯一实例
*/
public static ProductList getInstance(){
if (instance==null){
instance = new ProductList();
instance.productList = new ArrayList<>();
}
return instance;
}
/**
* 增加观察者(电商接口)
* @param observer 观察者
*/
public void addProductListObserver(Observer observer){
this.addObserver(observer);
}
/**
* 新增商品
* @param newProduct 新产品
*/
public void addProduct(String newProduct){
productList.add(newProduct);
System.out.println("产品列表新增了产品"+newProduct);
setChanged();//设置被观察者对象发生变化
notifyObservers(newProduct);//通知观察者,并传递新产品
}
}
JingDongObserver.class
package com.proxy.cn.Design_patterns.Observer_mode;
import java.util.Observable;
import java.util.Observer;
public class JingDongObserver implements Observer {
@Override
public void update(Observable o, Object product) {
String newProduct = (String) product;
System.out.println("发送新产品"+newProduct+"同步到京东商城");
}
}
TaoBaoObserver.class
package com.proxy.cn.Design_patterns.Observer_mode;
import java.util.Observable;
import java.util.Observer;
public class TaoBaoObserver implements Observer {
@Override
public void update(Observable o, Object product) {
String newProduct = (String) product;
System.out.println("发送新产品"+newProduct+"同步到淘宝商城");
}
}
main.class
package com.proxy.cn.Design_patterns.Observer_mode;
public class main {
public static void main(String[] args) {
ProductList observer = ProductList.getInstance();
TaoBaoObserver taoBaoObserver = new TaoBaoObserver();
JingDongObserver jingDongObserver = new JingDongObserver();
observer.addProductListObserver(taoBaoObserver);
observer.addProductListObserver(jingDongObserver);
observer.addProduct("新增产品01");
}
}