Java JDK自带的观察者设计模式
程序员文章站
2024-01-19 08:02:22
...
观察者是实现java.util.Observer接口
被观察者是继承java.util.Observable类
package com.cwq.beyond;
import java.util.Observable;
import java.util.Observer;
public class Temo {
public static void main(String[] args) {
PersonAll perAPerson = new PersonAll();
PersonAll perBPerson = new PersonAll();
PersonAll perCPerson = new PersonAll();
House house = new House(8000.00);
house.addObserver(perAPerson);
house.addObserver(perBPerson);
house.addObserver(perCPerson);
house.setPrice(900000);
}
}
class PersonAll implements Observer{
@Override
public void update(Observable o, Object arg) {
if (o instanceof House) {
if (arg instanceof Double) {
System.out.println("[人民关注],房价上涨:"+ arg);
}
}
}
}
class House extends Observable{ // 被观察者
private double price; // 被观察者
public House(Double price) {
this.price = price;
}
public void setPrice(double price) {
if (this.price < price) {
super.setChanged();
super.notifyObservers(price);
}
this.price = price;
}
}