24.12.14
实验 21:观察者模式
本次实验属于模仿型实验,通过本次实验学生将掌握以下内容:
1、理解观察者模式的动机,掌握该模式的结构;
2、能够利用观察者模式解决实际问题。
[实验任务一]:股票提醒
当股票的价格上涨或下降5%时,会通知持有该股票的股民,当股民听到价格上涨的消息时会买股票,当价格下降时会大哭一场。
实验要求:
1. 画出对应类图;
2. 提交源代码;
3. 注意编程规范。
- 类图:
- 源代码:
import java.util.ArrayList;
import java.util.List;
// 观察者接口
interface Observer {
void update(String stockName, double oldPrice, double newPrice);
}
// 被观察者接口
interface Subject {
void registerObserver(Observer observer);
void removeObserver(Observer observer);
void notifyObservers();
}
// Stock类 (被观察者)
class Stock implements Subject {
private String name;
private double price;
private List<Observer> observers;
private double previousPrice;
public Stock(String name, double price) {
this.name = name;
this.price = price;
this.previousPrice = price;
observers = new ArrayList<>();
}
public void setPrice(double newPrice) {
this.previousPrice = this.price;
this.price = newPrice;
if (Math.abs((newPrice - previousPrice) / previousPrice) >= 0.05) {
notifyObservers();
}
}
public double getPrice() {
return price;
}
public String getName() {
return name;
}
@Override
public void registerObserver(Observer observer) {
observers.add(observer);
}
@Override
public void removeObserver(Observer observer) {
observers.remove(observer);
}
@Override
public void notifyObservers() {
for (Observer observer : observers) {
observer.update(name, previousPrice, price);
}
}
}
// Stockholder类 (观察者)
class Stockholder implements Observer {
private String name;
public Stockholder(String name) {
this.name = name;
}
@Override
public void update(String stockName, double oldPrice, double newPrice) {
System.out.println("股民 " + name + " 收到通知:股票 " + stockName + " 价格从 " + oldPrice + " 变为 " + newPrice);
if (newPrice > oldPrice) {
System.out.println(name + ":价格上涨,买入股票!");
} else {
System.out.println(name + ":价格下跌,大哭一场!");
}
System.out.println("---------------------------");
}
}
// 测试类
public class Client {
public static void main(String[] args) {
Stock stock = new Stock("ABC", 100.0);
Stockholder s1 = new Stockholder("张三");
Stockholder s2 = new Stockholder("李四");
stock.registerObserver(s1);
stock.registerObserver(s2);
// 模拟股票价格变动
System.out.println("第一次价格变动:");
stock.setPrice(105.0); // 涨 5%
System.out.println("第二次价格变动:");
stock.setPrice(95.0); // 跌 10%
System.out.println("第三次价格变动:");
stock.setPrice(90.0); // 跌 5%
System.out.println("第四次价格变动:");
stock.setPrice(110.0); // 涨 22%
}
}