Created
March 23, 2011 22:30
-
-
Save ianbishop/884179 to your computer and use it in GitHub Desktop.
Simple message passing example in Ruby (1)
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
class Repeater | |
@@subscribers = [] | |
# Add the new subscriber to our list of subscribers | |
def subscribe(newSubscriber) | |
@@subscribers << newSubscriber | |
end | |
# Send the message to all of our subscribers | |
def broadcast(message) | |
@@subscribers.each { |subscriber| subscriber.accept(message) } | |
end | |
end | |
module Subscriber | |
# This will alert of us if we include subscriber | |
# but don't implement all of its methods | |
def accept(message) | |
raise "not implemented" | |
end | |
end | |
# Our first subscriber, Sub1 | |
class Sub1 | |
include Subscriber | |
def initialize(repeater) | |
@repeater = repeater | |
@repeater.subscribe(self) | |
end | |
# Simply print out the message on accepting | |
def accept(message) | |
puts "#{self.class} accepted #{message}" | |
end | |
# A method to allow us to send messages to the repeater | |
def send(message) | |
@repeater.broadcast(message) | |
end | |
end | |
#Our second subscriber, Sub2 | |
class Sub2 | |
include Subscriber | |
def initialize(repeater) | |
@repeater = repeater | |
@repeater.subscribe(self) | |
end | |
def accept(message) | |
puts "#{self.class} accepted #{message}" | |
end | |
end | |
r = Repeater.new | |
sub1 = Sub1.new(r) | |
# Send a message when Sub1 is the only subscriber | |
sub1.send("Hello World!") | |
sub2 = Sub2.new(r) | |
# Send a message when Sub2 has been added to the subscriber list | |
sub1.send("Hi, new guy!") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment