观察者模式(Observer Pattern):股票交易系统实战案例分析

627 阅读3分钟

image.png

肖哥弹架构 跟大家“弹弹” 业务中设计模式的使用,需要代码关注

欢迎 点赞,点赞,点赞。

关注公号Solomon肖哥弹架构获取更多精彩内容

在股票交易系统中,当股票价格发生变化时,系统需要实时通知所有订阅该股票的投资者。这包括发送实时价格更新、交易提醒等。

2. 为什么要使用观察者设计模式

观察者模式允许对象间的一对多依赖关系,当一个对象改变状态时,所有依赖于它的对象都会得到通知并自动更新。

3. 标准观察者设计模式图

4. 业务观察者设计模式图

5. 业务代码参考

    // 股票类,作为被观察的主题
    class Stock {
        private String name;
        private double price;
        private List<Investor> observers = new ArrayList<>();

        public Stock(String name) {
            this.name = name;
        }

        public void setPrice(double newPrice) {
            if (newPrice != this.price) {
                this.price = newPrice;
                notify();
            }
        }

        public void subscribe(Investor investor) {
            observers.add(investor);
        }

        public void unsubscribe(Investor investor) {
            observers.remove(investor);
        }

        public void notify() {
            for (Investor observer : observers) {
                observer.update(this, price);
            }
        }

        public String getName() {
            return name;
        }
    }

    // 投资者类,作为观察者
    class Investor {
        private String name;

        public Investor(String name) {
            this.name = name;
        }

        public void update(Stock stock, double newPrice) {
            // 投资者收到股票价格更新的逻辑
            System.out.println("Investor " + name + " is notified: " +
                    "Stock " + stock.getName() + " price updated to " + newPrice);
        }
    }

    // 客户端使用
    class StockTradingSystem {
        public static void main(String[] args) {
            Stock stock = new Stock("Tech Corp");

            Investor investor1 = new Investor("lili");
            Investor investor2 = new Investor("sasa");

            stock.subscribe(investor1);
            stock.subscribe(investor2);

            // 模拟股票价格更新
            stock.setPrice(120.5);
            stock.setPrice(130.75);
        }
    }

6. 使用观察者设计模式的好处

  • 解耦:股票价格更新逻辑与通知投资者的逻辑解耦。
  • 实时性:投资者可以实时接收到股票价格的更新。

7. 其他使用观察者设计模式场景参考

  • 社交媒体:用户发布动态时,通知关注者。
  • 消息系统:发送消息时,通知所有在线的接收者。

8. 可参考开源框架

  • Java Observer Pattern Implementation:Java标准库中的ObserverObservable类。

结论

观察者模式是一种适用于创建对象事件通知机制的设计模式,特别适合于实现分布式事件处理系统,如股票交易系统。

历史热点文章