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

The Strategy itself

And the extended Data classes

And the extended Strategy

And our test class.


Tomas said...

Hi Magnus,

I have often used the Strategy pattern in Java (including with Generics) and while it indeed can be a nice pattern to use, it can also be somewhat frustrating when you want to apply it for trying to do small-level refactorings and avoid some code small duplications.

The reason is that sometimes the resulting code does not look so much better, considering all the duplication of creating the objects that implement the small interface and its method signatures.

If you instead use a language (e.g. Scala which is JVM-compatible with Java) that provides you with the option of using a so called "first-class functions", then you can reduce some of the boilerplating code.

The kind of redundant Java Strategy code I am talking about is not visible in your example (at least not as it looked 2010-02-12) but for an example (with Generics), you can see the URL http://www.scalaforum.se/scala-for-java-developers/using-scala-functions-to-reduce-duplication/

Having said this, I still think it can be reasonable to define a Strategy interface with good semantics, in such a language, even if the interface only has one method, since it can improve the readability/maintainability which I consider to be far more important than the initial overhead of creating an interface.

/ Tomas

pranav said...

Hi Magnus, very good example of strategy pattern and generics.
Thanks for simple example, which is easy to understand.

what is class in java said...

Great tutorial. Effective Java book also has a very good example on Strategy pattern involving Comparator class for generics, you can also see How Generics works in Java

Anonymous said...

Great Example !!

The Book Head First Design Patterns explains this too pretty well.