10.28

实验 21:观察者模式

本次实验属于模仿型实验,通过本次实验学生将掌握以下内容:

1、理解观察者模式的动机,掌握该模式的结构;

2、能够利用观察者模式解决实际问题。

 

[实验任务一]:股票提醒

当股票的价格上涨或下降5%时,会通知持有该股票的股民,当股民听到价格上涨的消息时会买股票,当价格下降时会大哭一场。

实验要求:

1. 画出对应类图;

 

2. 提交源代码;

import abc


class Stock:
    def __init__(self, symbol, price):
        self.symbol = symbol
        self.price = price
        self.investors = []

    def setPrice(self, new_price):
        old_price = self.price
        self.price = new_price
        if abs((self.price - old_price) / old_price) >= 0.05:
            self.notifyInvestors(old_price, self.price)

    def getPrice(self):
        return self.price

    def attach(self, investor):
        self.investors.append(investor)

    def detach(self, investor):
        self.investors.remove(investor)

    def notifyInvestors(self, old_price, new_price):
        for investor in self.investors:
            investor.update(old_price, new_price)


class Investor(abc.ABC):
    def __init__(self, name):
        self.name = name

    @abc.abstractmethod
    def update(self, old_price, new_price):
        pass


class BullishInvestor(Investor):
    def __init__(self, name):
        super().__init__(name)

    def update(self, old_price, new_price):
        if new_price > old_price:
            print(f"{self.name} 听到股票 {new_price} 上涨的消息,决定买入股票。")


class BearishInvestor(Investor):
    def __init__(self, name):
        super().__init__(name)

    def update(self, old_price, new_price):
        if new_price < old_price:
            print(f"{self.name} 听到股票 {new_price} 下跌的消息,大哭一场。")


if __name__ == "__main__":
    stock = Stock("AAPL", 100)

    bullish_investor = BullishInvestor("张三")
    bearish_investor = BearishInvestor("李四")

    stock.attach(bullish_investor)
    stock.attach(bearish_investor)

    stock.setPrice(106)
    stock.setPrice(95)

 

3. 注意编程规范。

 

 

posted @ 2024-11-27 08:22  The-rich  阅读(7)  评论(0)    收藏  举报