Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
modifying chain of responsibility pattern
- Loading branch information
Showing
1 changed file
with
13 additions
and
22 deletions.
There are no files selected for viewing
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -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 |