Patterns / Behavioral patterns
image

# Handler
class Rescuer
    def initialize(code, rescuer)
        @code, @next = code, rescuer
    end

    # HandleRequest()
    def help(code)
        if @code == code
            to_help()
        elsif @next != nil
            @next.help(code)
        end
    end
end

# ConcreteHandler
class Firefighter < Rescuer
    def initialize(rescuer)
        super(1, rescuer)
    end

    def to_help()
        puts "call firefighters"
    end
end

# ConcreteHandler
class Police < Rescuer
    def initialize(rescuer)
        super(2, rescuer)
    end

    def to_help()
        puts "call the police"
    end
end

    # ConcreteHandler
class Ambulance < Rescuer
    def initialize
        super(3nil)
    end

    def to_help()
        puts "call an ambulance"
    end
end

ambulance = Ambulance.new
police = Police.new(ambulance)
firefighter = Firefighter.new(police)
firefighter.help(1)
# printed: call firefighters
firefighter.help(2)
# printed: call the police
firefighter.help(3)
# printed: call an ambulance


Avoid coupling the sender of a request to its receiver by giving more than one object a chance to handle the request. Chain the receiving objects and pass the request along the chain until an object handles it.