2018-12-12 07:39:52 +03:00
|
|
|
// Package main serves as an example application that makes use of the chain of responsibility pattern.
|
|
|
|
package main
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
|
|
|
)
|
|
|
|
|
2019-03-14 08:10:40 +03:00
|
|
|
type request struct {
|
|
|
|
value float64
|
|
|
|
}
|
|
|
|
|
2018-12-12 07:39:52 +03:00
|
|
|
//NumberProcessor has the processor method which will tell if the value is negative, positive or zero
|
|
|
|
type NumberProcessor interface {
|
2019-03-14 08:10:40 +03:00
|
|
|
process(request)
|
2018-12-12 07:39:52 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
//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.
|
2019-03-14 08:10:40 +03:00
|
|
|
func (zero ZeroHandler) process(req request) {
|
|
|
|
|
|
|
|
if req.value == 0.0 {
|
2018-12-12 07:39:52 +03:00
|
|
|
fmt.Print("its zero")
|
|
|
|
} else {
|
2019-03-14 08:10:40 +03:00
|
|
|
zero.numberProcessor.process(req)
|
2018-12-12 07:39:52 +03:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
//For returning its negative if the value is negative.
|
2019-03-14 08:10:40 +03:00
|
|
|
func (negative NegativeHandler) process(req request) {
|
|
|
|
if req.value < 0 {
|
2018-12-12 07:39:52 +03:00
|
|
|
fmt.Print("its a negative number")
|
|
|
|
} else {
|
2019-03-14 08:10:40 +03:00
|
|
|
negative.numberProcessor.process(req)
|
2018-12-12 07:39:52 +03:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
//For returning its positive if the value is positive.
|
2019-03-14 08:10:40 +03:00
|
|
|
func (positve PositiveHandler) process(req request) {
|
|
|
|
if req.value > 0 {
|
2018-12-12 07:39:52 +03:00
|
|
|
fmt.Print("its a postitive number")
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func main() {
|
|
|
|
//initialising the chain of actions.
|
|
|
|
zeroHandler := ZeroHandler{NegativeHandler{PositiveHandler{}}}
|
2019-03-14 08:10:40 +03:00
|
|
|
|
|
|
|
zeroHandler.process(request{10})
|
|
|
|
zeroHandler.process(request{-19.9})
|
|
|
|
zeroHandler.process(request{0})
|
2018-12-12 07:39:52 +03:00
|
|
|
}
|