Last active
September 30, 2015 00:44
-
-
Save mdamaceno/da0e39f15d8f2e93766f to your computer and use it in GitHub Desktop.
Observer Pattern in Ruby
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require "observer" | |
class Ticker ### Periodically fetch a stock price. | |
include Observable | |
def initialize(symbol) | |
@symbol = symbol | |
end | |
def run | |
last_price = nil | |
loop do | |
price = Price.fetch(@symbol) | |
print "Current price: #{price}\n" | |
if price != last_price | |
changed # notify observers | |
last_price = price | |
notify_observers(Time.now, price) | |
end | |
sleep 1 | |
end | |
end | |
end | |
class Price ### A mock class to fetch a stock price (60 - 140). | |
def self.fetch(symbol) | |
60 + rand(80) | |
end | |
end | |
class Warner ### An abstract observer of Ticker objects. | |
def initialize(ticker, limit) | |
@limit = limit | |
ticker.add_observer(self) | |
end | |
end | |
class WarnLow < Warner | |
def update(time, price) # callback for observer | |
if price < @limit | |
print "--- #{time.to_s}: Price below #@limit: #{price}\n" | |
end | |
end | |
end | |
class WarnHigh < Warner | |
def update(time, price) # callback for observer | |
if price > @limit | |
print "+++ #{time.to_s}: Price above #@limit: #{price}\n" | |
end | |
end | |
end | |
ticker = Ticker.new("MSFT") | |
WarnLow.new(ticker, 80) | |
WarnHigh.new(ticker, 120) | |
ticker.run | |
=begin | |
Current price: 83 | |
Current price: 75 | |
--- Sun Jun 09 00:10:25 CDT 2002: Price below 80: 75 | |
Current price: 90 | |
Current price: 134 | |
+++ Sun Jun 09 00:10:25 CDT 2002: Price above 120: 134 | |
Current price: 134 | |
Current price: 112 | |
Current price: 79 | |
--- Sun Jun 09 00:10:25 CDT 2002: Price below 80: 79 | |
=end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment