1
0
Fork 0
mirror of https://github.com/tmrts/go-patterns.git synced 2025-04-02 20:56:12 +03:00
This commit is contained in:
Akshay Nambiar 2019-03-14 05:11:02 +00:00 committed by GitHub
commit 3f63e2dc9a
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
2 changed files with 72 additions and 0 deletions

View file

@ -0,0 +1,7 @@
# Chain of responsibility
The [Chain of responsibility](https://en.wikipedia.org/wiki/Chain-of-responsibility_pattern) pattern is a design pattern consisting of a source of command objects and a series of processing objects. Each processing object contains logic that defines the types of command objects that it can handle; the rest are passed to the next processing object in the chain.
#implementation
An example showing implementation and usage can be found in [main.go](chain_of_responsibility/main.go).

View file

@ -0,0 +1,65 @@
// Package main serves as an example application that makes use of the chain of responsibility pattern.
package main
import (
"fmt"
)
type request struct {
value float64
}
//NumberProcessor has the processor method which will tell if the value is negative, positive or zero
type NumberProcessor interface {
process(request)
}
//ZeroHandler handles the value which is zero
type ZeroHandler struct {
numberProcessor NumberProcessor
}
//PositiveHandler handles the value which is positive
type PositiveHandler struct {
numberProcessor NumberProcessor
}
//NegativeHandler handles the value which is negative
type NegativeHandler struct {
numberProcessor NumberProcessor
}
//For returning zero if the value is zero.
func (zero ZeroHandler) process(req request) {
if req.value == 0.0 {
fmt.Print("its zero")
} else {
zero.numberProcessor.process(req)
}
}
//For returning its negative if the value is negative.
func (negative NegativeHandler) process(req request) {
if req.value < 0 {
fmt.Print("its a negative number")
} else {
negative.numberProcessor.process(req)
}
}
//For returning its positive if the value is positive.
func (positve PositiveHandler) process(req request) {
if req.value > 0 {
fmt.Print("its a postitive number")
}
}
func main() {
//initialising the chain of actions.
zeroHandler := ZeroHandler{NegativeHandler{PositiveHandler{}}}
zeroHandler.process(request{10})
zeroHandler.process(request{-19.9})
zeroHandler.process(request{0})
}