
代码示例:
观察者模式是一种行为设计模式,允许一个对象(称为主题)在状态发生变化时通知其他对象(称为观察者)。这种模式在 Ruby 中的应用非常广泛,尤其是在 GUI 组件中。以下是一个详细的 Ruby 示例,展示如何实现观察者模式。
示例:股票价格监控系统
- 定义观察者接口
观察者接口定义了观察者需要实现的方法,通常是一个 update 方法。
ruby复制
module Observer
def update(*args)
raise NotImplementedError, ‘You must implement the update method’
end
end - 创建主题类
主题类负责管理观察者列表,并在状态变化时通知它们。
ruby复制
class Subject
def initialize
@observers = []
end
def attach(observer)
@observers << observer
end
def detach(observer)
@observers.delete(observer)
end
def notify_observers(*args)
@observers.each { |observer| observer.update(*args) }
end
end
3. 创建具体主题类
具体主题类继承自主题类,并在状态变化时调用通知方法。
ruby复制
class StockSubject < Subject
attr_accessor :price
def initialize(symbol)
super()
@symbol = symbol
@price = 0
end
def update_price(new_price)
@price = new_price
notify_observers(@symbol, @price)
end
end
4. 创建具体观察者类
具体观察者类实现了观察者接口,并根据主题的状态变化做出反应。
ruby复制
class HighPriceObserver
include Observer
def initialize(threshold)
@threshold = threshold
end
def update(symbol, price)
puts “#{symbol} price is high: #{price}” if price > @threshold
end
end
class LowPriceObserver
include Observer
def initialize(threshold)
@threshold = threshold
end
def update(symbol, price)
puts “#{symbol} price is low: #{price}” if price < @threshold
end
end
5. 客户端代码
客户端代码创建主题和观察者,并将观察者附加到主题上。
ruby复制
创建股票主题
stock = StockSubject.new(“AAPL”)
创建观察者
high_observer = HighPriceObserver.new(150)
low_observer = LowPriceObserver.new(100)
将观察者附加到主题
stock.attach(high_observer)
stock.attach(low_observer)
模拟股票价格变化
stock.update_price(160)
stock.update_price(90)
输出结果
复制
AAPL price is high: 160
AAPL price is low: 90
说明
在这个例子中,StockSubject 是主题类,它管理着股票价格的变化。HighPriceObserver 和 LowPriceObserver 是观察者类,它们分别在股票价格高于或低于某个阈值时发出警告。当股票价格发生变化时,主题会通知所有观察者,观察者根据自己的逻辑进行处理。
这种模式的优点是解耦了主题和观察者之间的关系,使得系统更加灵活和可扩展。
喜欢本文,请点赞、收藏和关注!
如能打赏、那更好了!
**如有朋友需要杭州社保挂靠的,可以在评论区或联系博主!
本人有朋友公司需要有计算机专业人员的社保缴纳。因为是新公司
**
1061

被折叠的 条评论
为什么被折叠?



