-
-
Save monogot/f30fc1debc007568ac3a7ba1f8dd811f to your computer and use it in GitHub Desktop.
Example of using Observable in Ruby
This file contains hidden or 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 CoffeeShop | |
include Observable | |
attr_reader :customers | |
def initialize(name, capacity) | |
@name = name | |
@capacity = capacity | |
@customers = [] | |
end | |
def enter(customer) | |
unless full? | |
changed | |
@customers.push(customer) | |
notify_observers(Time.now) | |
end | |
end | |
def depart(customer) | |
unless empty? | |
changed | |
@customers.delete(customer) | |
notify_observers(Time.now) | |
end | |
end | |
def full? | |
@customers.count >= @capacity | |
end | |
def empty? | |
@customers.count.zero? | |
end | |
end | |
class CoffeeShopObserver | |
def initialize(shop) | |
@shop = shop | |
@shop.add_observer(self) | |
end | |
end | |
class CoffeeShopEmptyObserver < CoffeeShopObserver | |
def update(time) | |
if @shop.empty? | |
puts "#{time}: The shop is EMPTY so some staff can go home." | |
end | |
end | |
end | |
class CoffeeShopFullObserver < CoffeeShopObserver | |
def update(time) | |
if @shop.full? | |
puts "#{time}: The shop is FULL - quick call more staff!" | |
end | |
end | |
end |
This file contains hidden or 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
coffee_shop = CoffeeShop.new("Costa", 3) | |
CoffeeShopEmptyObserver.new(coffee_shop) | |
CoffeeShopFullObserver.new(coffee_shop) | |
potential_customers = %w(Bob Harry William Darren Brian Susan Kelly John Kevin) | |
customer_actions = [:enter, :enter, :depart] #enter in twice to try and encourage more customers! | |
20.times do | |
action = customer_actions.sample | |
if action == :enter | |
customer = potential_customers.sample | |
potential_customers.delete(customer) | |
puts "Entering: #{customer}" | |
coffee_shop.enter(customer) | |
else | |
unless coffee_shop.empty? | |
customer = coffee_shop.customers.sample | |
puts "Leaving #{customer}" | |
potential_customers.push(customer) | |
coffee_shop.depart(customer) | |
end | |
end | |
sleep 0.1 | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment