Skip to content

Commit

Permalink
modifying chain of responsibility pattern
Browse files Browse the repository at this point in the history
  • Loading branch information
shvets committed Aug 5, 2010
1 parent 886280e commit 4ceb7a4
Showing 1 changed file with 13 additions and 22 deletions.
35 changes: 13 additions & 22 deletions behavioral/chain_of_responsibility.rb
@@ -1,50 +1,41 @@
# chain-of-responsibility.bsh
# chain-of-responsibility.rb

# Avoid coulpling the sender of a request to it's receiver by giving more than
# one object a chance to handle the request. Chain the receiving object and pass
# one object a chance to handle the request. Chains the receiving object and passes
# the request along the chain until an object handles it.

# 1. type interface

class Handler
class Chain
def handle
end

def next_handler=(handler)
def initialize(next_in_chain)
@next_in_chain = next_in_chain
end
end

# 2. type implementation

class MyHandler < Handler
def initialize(name)
class MyChain < Chain
def initialize(name, next_in_chain=nil)
super(next_in_chain)

@name = name
end

def handle
puts "Handling by " + @name + "."

if(@next_handler != nil)
@next_handler.handle
if(@next_in_chain != nil)
@next_in_chain.handle
end
end

def next_handler=(next_handler)
@next_handler = next_handler
end
end

# 3. test

handler1 = MyHandler.new("handler1")
handler2 = MyHandler.new("handler2")
handler3 = MyHandler.new("handler3")
handler4 = MyHandler.new("handler4")
handler5 = MyHandler.new("handler5")
chain = MyChain.new("chain1", MyChain.new("chain2", MyChain.new("chain3", MyChain.new("chain5", MyChain.new("chain4")))))

handler1.next_handler = handler2
handler2.next_handler = handler5
handler5.next_handler = handler3
handler3.next_handler = handler4
chain.handle

handler1.handle

0 comments on commit 4ceb7a4

Please sign in to comment.