If we were using Java JDK 1.4 we have to do down-casting in the concrete strategy classes, but with Generics that is not necessary.
The Strategy Context/Client
package se.msc.examples.generics;
public abstract class Data<D extends Data<D>> {
public static final Strategy<FooData> FOO_STRATEGY = new FooStrategy();
public static final Strategy<BarData> BAR_STRATEGY = new BarStrategy();
}
The Strategy itself
package se.msc.examples.generics;
public abstract class Strategy<D extends Data<?>> {
public abstract String exec(D data);
}
And the extended Data classes
package se.msc.examples.generics;
public class FooData extends Data<FooData> {
public final double value;
public FooData(double value) {
this.value = value;
}
public double getValue() {
return value;
}
}
And the extended Strategy
package se.msc.examples.generics;
public class FooStrategy extends Strategy<FooData> {
public String exec(FooData data) {
return "Hi " + data.getValue();
}
}
And our test class.
package se.msc.examples.generics;
import static org.junit.Assert.*;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
public class StrategyTest {
@BeforeClass
public static void oneTimeSetUp() throws Exception {
}
@AfterClass
public static void oneTimeTearDown() {
}
@Before
public void setUp() throws Exception {
}
@After
public void tearDown() throws Exception {
}
@Test
public void testFooStrategy() throws Exception {
assertEquals("Hi 3.0", Data.FOO_STRATEGY.exec(new FooData(3)));
}
}
No comments:
Post a Comment