February 1, 2010

Java Generics Example Strategy Pattern

With Java Generics Java has continued its path to make it's language more strong typed, with comparison to all new dynamic language where they have thrown out strong typing. But Java Generics can also be hard to understand and one of the best example to show the main benefit with it is the strategy pattern. Lets start to look of a example.


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: