软件设计-Tutorial21
类图:
```mermaid classDiagram class Stock { -String stockName -double price -List~Investor~ investors +Stock(String, double) +void addInvestor(Investor) +void removeInvestor(Investor) +void setPrice(double) -void notifyPriceIncrease(double) -void notifyPriceDecrease(double) } class Investor { <<interface>> +void onPriceIncrease(double) +void onPriceDecrease(double) } class InvestorImpl { -String name +InvestorImpl(String) +void onPriceIncrease(double) +void onPriceDecrease(double) } Stock o-- Investor : 观察者 InvestorImpl ..|> Investor Stock --> InvestorImpl : 通知 ```
源码:
package Tutorial21; import java.util.ArrayList; import java.util.List; // 观察者接口 interface Investor { void onPriceIncrease(double price); void onPriceDecrease(double price); } // 具体的观察者类 class InvestorImpl implements Investor { private String name; public InvestorImpl(String name) { this.name = name; } @Override public void onPriceIncrease(double price) { System.out.println(name + "收到消息:股票价格上涨至 " + price + ",买入股票!"); } @Override public void onPriceDecrease(double price) { System.out.println(name + "收到消息:股票价格下跌至 " + price + ",大哭一场!"); } } // 被观察者类 class Stock { private String stockName; private double price; private List<Investor> investors = new ArrayList<>(); public Stock(String stockName, double price) { this.stockName = stockName; this.price = price; } // 添加观察者 public void addInvestor(Investor investor) { investors.add(investor); } // 移除观察者 public void removeInvestor(Investor investor) { investors.remove(investor); } // 设置新价格并判断是否通知观察者 public void setPrice(double newPrice) { double changePercentage = ((newPrice - price) / price) * 100; if (Math.abs(changePercentage) >= 5) { System.out.println("\n股票 " + stockName + " 的价格变动了 " + String.format("%.2f", changePercentage) + "%!"); if (changePercentage > 0) { notifyPriceIncrease(newPrice); } else { notifyPriceDecrease(newPrice); } } // 更新价格 this.price = newPrice; } // 通知价格上涨的观察者 private void notifyPriceIncrease(double price) { for (Investor investor : investors) { investor.onPriceIncrease(price); } } // 通知价格下跌的观察者 private void notifyPriceDecrease(double price) { for (Investor investor : investors) { investor.onPriceDecrease(price); } } } // 测试类 public class ObserverExample { public static void main(String[] args) { // 创建股票 Stock stock = new Stock("科技股份", 100.0); // 添加观察者 Investor investor1 = new InvestorImpl("小张"); Investor investor2 = new InvestorImpl("小李"); stock.addInvestor(investor1); stock.addInvestor(investor2); // 价格变化测试 stock.setPrice(105.0); // 上涨5% stock.setPrice(95.0); // 下跌9.5% stock.setPrice(100.0); // 不通知变化 } }