Created
August 13, 2020 14:10
-
-
Save zapkub/a41d20165c9a437dac126bced974894b to your computer and use it in GitHub Desktop.
math strategy example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import "fmt" | |
// strategy: square, factorial, absolute | |
// input : integer | |
// output : integer | |
type MathStrategy interface { | |
assert(strategyType string) bool | |
execute(input int) int | |
} | |
type SquareMathStrategy struct{} | |
func (s *SquareMathStrategy) assert(strategyType string) bool { | |
return strategyType == "square" | |
} | |
func (s *SquareMathStrategy) execute(input int) int { | |
return input * input | |
} | |
type FactorialMathStrategy struct{} | |
func (s *FactorialMathStrategy) assert(strategyType string) bool { | |
return strategyType == "factorial" | |
} | |
func (s *FactorialMathStrategy) execute(input int) int { | |
var result = input | |
for i := input - 1; i > 0; i-- { | |
result = result * i | |
} | |
return result | |
} | |
type calculator struct { | |
strategyList []MathStrategy | |
} | |
func (c *calculator) cal(input int, strategyType string) int { | |
for _, st := range c.strategyList { | |
if st.assert(strategyType) { | |
return st.execute(input) | |
} | |
} | |
panic("unknown strategy " + strategyType) | |
} | |
var defaultCalculator = &calculator{ | |
strategyList: []MathStrategy{ | |
&SquareMathStrategy{}, | |
&FactorialMathStrategy{}, | |
}, | |
} | |
func main() { | |
var result = defaultCalculator.cal(4, "square") | |
fmt.Println(result) | |
result = defaultCalculator.cal(4, "factorial") | |
fmt.Println(result) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment