From 33cddd734073436934994aa4b8d2fb3d2c97c372 Mon Sep 17 00:00:00 2001 From: "akshay.nambiar" Date: Wed, 12 Dec 2018 10:09:52 +0530 Subject: [PATCH] behavioral/chain_of_responsibility: implemented chain of responsibility pattern. --- behavioral/chain_of_responsibility.md | 7 +++ behavioral/chain_of_responsibility/main.go | 59 ++++++++++++++++++++++ 2 files changed, 66 insertions(+) create mode 100644 behavioral/chain_of_responsibility.md create mode 100644 behavioral/chain_of_responsibility/main.go diff --git a/behavioral/chain_of_responsibility.md b/behavioral/chain_of_responsibility.md new file mode 100644 index 0000000..8447dcf --- /dev/null +++ b/behavioral/chain_of_responsibility.md @@ -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). diff --git a/behavioral/chain_of_responsibility/main.go b/behavioral/chain_of_responsibility/main.go new file mode 100644 index 0000000..9f2fff7 --- /dev/null +++ b/behavioral/chain_of_responsibility/main.go @@ -0,0 +1,59 @@ +// Package main serves as an example application that makes use of the chain of responsibility pattern. +package main + +import ( + "fmt" +) + +//NumberProcessor has the processor method which will tell if the value is negative, positive or zero +type NumberProcessor interface { + process(int) +} + +//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(value int) { + if value == 0 { + fmt.Print("its zero") + } else { + zero.numberProcessor.process(value) + } +} + +//For returning its negative if the value is negative. +func (negative NegativeHandler) process(value int) { + if value < 0 { + fmt.Print("its a negative number") + } else { + negative.numberProcessor.process(value) + } +} + +//For returning its positive if the value is positive. +func (positve PositiveHandler) process(value int) { + if value > 0 { + fmt.Print("its a postitive number") + } +} + +func main() { + //initialising the chain of actions. + zeroHandler := ZeroHandler{NegativeHandler{PositiveHandler{}}} + zeroHandler.process(10) + zeroHandler.process(-19) + zeroHandler.process(0) +}