Add strategy pattern

This commit is contained in:
Tamer Tas
2015-12-23 15:46:15 +02:00
parent cfd83425b6
commit aeca31fe3d
3 changed files with 104 additions and 48 deletions

39
strategy.go Normal file
View File

@@ -0,0 +1,39 @@
package main
import "fmt"
type Operator interface {
Apply(int, int) int
}
type Operation struct {
Operator Operator
}
func (o *Operation) Operate(leftValue, rightValue int) int {
return o.Operator.Apply(leftValue, rightValue)
}
type Multiplication struct{}
func (Multiplication) Apply(lval, rval int) int {
return lval * rval
}
type Addition struct{}
func (Addition) Apply(lval, rval int) int {
return lval + rval
}
func main() {
mult := Operation{Multiplication{}}
// Outputs 15
fmt.Println(mult.Operate(3, 5))
pow := Operation{Addition{}}
// Outputs 8
fmt.Println(pow.Operate(3, 5))
}