Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Code Block
interface Calc {
	    def execute(n, m)
}

class CalcByMult implements Calc {
	    def execute(n, m) { n * m }
}

class CalcByManyAdds implements Calc {
	    def execute(n, m) {
		        def result = 0
		        n.times{
			            result += m
		}
		        }
        return result
	    }
}

def sampleData = [
	    [3, 4, 12],
	    [5, -5, -25]
]

Calc[] multiplicationStrategies = [
    new CalcByMult(),
    new CalcByManyAdds()
]

sampleData.each{ data ->
	    multiplicationStrategies.each{ calc ->
		        assert data[2] == calc.execute(data[0], data[1])
	    }
}

Here we have defined an interface Calc which our concrete strategy classes will implement (we could also have used an abstract class). We then defined two algorithms for doing simple multiplication: CalcByMult the normal way, and CalcByManyAdds using only addition (don't try this one using negative numbers - yes we could fix this but it would just make the example longer). We then use normal polymorphism to invoke the algorithms.

...

Code Block
def multiplicationStrategies = [
    { n, m -> n * m },
    { n, m -> def result = 0; n.times{ result += m }; result }
]

def sampleData = [
	    [3, 4, 12],
	    [5, -5, -25]
]

sampleData.each{ data ->
	    multiplicationStrategies.each{ calc ->
		        assert data[2] == calc(data[0], data[1])
	    }
}