定义:
定义观察者和被观察者两种角色,当被观察者属性发生变化的时候,观察者会给予响应.
要点:
(1)定义观察者和被观察者两种角色
(2)给被观察者绑定观察者
(3)当被观察者属性发生变化的时候,触发观察者的响应事件
实例:
1.定义被观察者类型
import java.util.Observable;
public class Product extends Observable {
private String id;
private String name;
private double price;
public Product(){
}
public Product( String id,String name,double price ){
this.id = id;
this.name = name;
this.price= price;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public void changed(){
setChanged();
}
}
2. 定义响应通知
public interface Notification {
public String getMessage() throws Exception;
}
public abstract class AbstractNotification implements Notification{
protected String productId;
protected String message;
public AbstractNotification(){
}
public AbstractNotification( String productId,String message ){
this.productId = productId;
this.message = message;
}
@Override
public String getMessage() throws Exception {
return message;
}
}
public class NameNotification extends AbstractNotification {
private String name;
private String nameUpdated;
public NameNotification(){
}
public NameNotification( String id,String name,String nameUpdated ){
this.productId = id;
this.name = name;
this.nameUpdated = nameUpdated;
}
@Override
public String getMessage() throws Exception {
StringBuilder sb = new StringBuilder();
sb.append("\n产品编号:"+productId);
sb.append("\n原始名字:"+name);
sb.append("\n更改后的名字:"+nameUpdated);
message = sb.toString();
return super.getMessage();
}
}
3.定义观察者
import java.util.Observable;
import java.util.Observer;
public class ProductObserver implements Observer {
@Override
public void update(Observable obj, Object notification ) {
Product product = (Product)obj;
if( product instanceof Product ){
Notification no = (Notification)notification;
try {
System.out.println(no.getMessage());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
4.测试
import java.util.Observer;
public class Test {
/**
* @param args
*/
public static void main(String[] args) {
Product product = new Product("3099876","纯棉衬衫",89.0);
Observer productObserver = new ProductObserver();
product.addObserver(productObserver);
String nameTemp = product.getName();
String name = "优质衬衫";
product.setName(name);
product.changed();
product.notifyObservers( new NameNotification(product.getId(),nameTemp,name));
}
}