

代码示例:
观察者模式是一种行为设计模式,允许一个对象(称为主题)在状态发生变化时通知其他对象(称为观察者)。这种模式在 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 是观察者类,它们分别在股票价格高于或低于某个阈值时发出警告。当股票价格发生变化时,主题会通知所有观察者,观察者根据自己的逻辑进行处理。
这种模式的优点是解耦了主题和观察者之间的关系,使得系统更加灵活和可扩展。
喜欢本文,请点赞、收藏和关注!
如能打赏、那更好了!
**如有朋友需要杭州社保挂靠的,可以在评论区或联系博主!
本人有朋友公司需要有计算机专业人员的社保缴纳。因为是新公司
**# 代码示例:
以下是一个详细的 Ruby 中观察者模式的实现示例,基于天气数据变化通知显示元素的场景:
观察者接口定义
首先定义观察者接口,确保所有观察者类都实现 update 方法。
ruby复制
module Observer
def update(data)
raise NotImplementedError, ‘You must implement the update method’
end
end
主题类实现
主题类负责管理观察者列表,并在状态变化时通知观察者。
ruby复制
class WeatherData
attr_reader :temperature, :humidity, :pressure
def initialize
@observers = []
end
def register_observer(observer)
@observers << observer
end
def remove_observer(observer)
@observers.delete(observer)
end
def notify_observers
@observers.each { |observer| observer.update(self) }
end
def set_measurements(temperature, humidity, pressure)
@temperature = temperature
@humidity = humidity
@pressure = pressure
notify_observers
end
end
具体观察者类实现
定义具体的观察者类,它们将根据天气数据的变化做出反应。
ruby复制
class CurrentConditionsDisplay
include Observer
def update(weather_data)
@temperature = weather_data.temperature
@humidity = weather_data.humidity
display
end
def display
puts “Current conditions: #{@temperature}F degrees and #{@humidity}% humidity”
end
end
class StatisticsDisplay
include Observer
def initialize
@temperatures = []
@humidities = []
end
def update(weather_data)
@temperatures << weather_data.temperature
@humidities << weather_data.humidity
display
end
def display
avg_temp = @temperatures.sum / @temperatures.size.to_f
avg_humidity = @humidities.sum / @humidities.size.to_f
puts “Avg/Max/Min temperature: #{avg_temp}/#{ @temperatures.max}/#{ @temperatures.min}”
puts “Avg/Max/Min humidity: #{avg_humidity}/#{ @humidities.max}/#{ @humidities.min}”
end
end
使用示例
创建天气数据对象和观察者对象,并注册观察者。
ruby复制
weather_data = WeatherData.new
current_display = CurrentConditionsDisplay.new
statistics_display = StatisticsDisplay.new
weather_data.register_observer(current_display)
weather_data.register_observer(statistics_display)
weather_data.set_measurements(80, 65, 30.4)
weather_data.set_measurements(82, 70, 29.2)
weather_data.set_measurements(78, 90, 29.2)
输出结果
运行上述代码后,输出如下:
复制
Current conditions: 80F degrees and 65% humidity
Avg/Max/Min temperature: 80.0/80.0/80.0
Avg/Max/Min humidity: 65.0/65.0/65.0
Current conditions: 82F degrees and 70% humidity
Avg/Max/Min temperature: 81.0/82.0/80.0
Avg/Max/Min humidity: 67.5/70.0/65.0
Current conditions: 78F degrees and 90% humidity
Avg/Max/Min temperature: 80.0/82.0/78.0
Avg/Max/Min humidity: 75.0/90.0/65.0
分析
解耦:观察者模式使得 WeatherData 类与具体的显示类解耦,WeatherData 类无需知道观察者的具体实现。
动态性:观察者可以在运行时动态添加或移除。
适用场景:适用于一个对象的状态变化需要通知多个其他对象的场景。
喜欢本文,请点赞、收藏和关注!
如能打赏、那更好了!
**如有朋友需要杭州社保挂靠的,可以在评论区或联系博主!
本人有朋友公司需要有计算机专业人员的社保缴纳。因为是新公司
**
Ruby 实现观察者模式代码示例
835

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



