Chain of Responsibility

Many times, the commands described previously might need handling such that we want a receiver to do work only when it is able to, and it's not then hand off the command to someone else next in the chain. For example, for the reports use case, we might want to handle authenticated and unauthenticated users differently.

The Chain of Responsibility pattern enables this by chaining a set of receiver objects. The receiver at the head of the chain tries to handle the command first, and if it's not able to handle it, delegates it to the next.

The sample code is given here:

type ChainedReceiver struct {
canHandle string
next *ChainedReceiver
}

func (r *ChainedReceiver) SetNext(next *ChainedReceiver) {
r.next = next
}

func (r *ChainedReceiver) Finish() error {
fmt.Println(r.canHandle, " Receiver Finishing")
return nil
}

func (r *ChainedReceiver) Handle(what string) error {
// Check if this receiver can handle the command
if what==r.canHandle {
// handle the command here
return r.Finish()
} else if r.next != nil {
// delegate to the next guy
return r.next.Handle(what)
} else {
fmt.Println("No Receiver could handle the request!")
return errors.New("No Receiver to Handle")
}
}

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset