Modify strategy pattern

This commit is contained in:
Tamer Tas
2016-01-03 07:03:20 +02:00
parent b10a4f9cac
commit b1ddd2651b
2 changed files with 19 additions and 15 deletions

25
strategy/strategy.go Normal file
View File

@@ -0,0 +1,25 @@
package strategy
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
}

18
strategy/strategy_test.go Normal file
View File

@@ -0,0 +1,18 @@
package strategy
import "testing"
func TestMultiplicationStrategy(t *testing.T) {
mult := Operation{Multiplication{}}
if res := mult.Operate(3, 5); res != 15 {
t.Errorf("Multiplication.Operate(3, 5) expected 15 got %q", res)
}
}
func TestAdditionStrategy(t *testing.T) {
add := Operation{Addition{}}
if res := add.Operate(3, 5); res != 8 {
t.Errorf("Addition.Operate(3, 5) expected 8 got %q", res)
}
}