File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes OO, Patterns, UML and Refactoring and the fly likes Strategy Pattern With Generics Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Engineering » OO, Patterns, UML and Refactoring
Bookmark "Strategy Pattern With Generics" Watch "Strategy Pattern With Generics" New topic

Strategy Pattern With Generics

Theodore David Williams
Ranch Hand

Joined: Dec 21, 2009
Posts: 102
I am messing around with design patterns (I am still new) and I was trying to write some code to take advantage of generics.

I.E. I was wondering how someone might implement the strategy pattern if the return type on the interfaces method could be different. Some code would probably help explain.

Seems simple enough so far. But here is where I get stuck. How can I inject a concrete 'stuff' implementation into another class at runtime to get a certain behavior but still take advantage of type safety.

I have been thinking about this for a few days and I am really stumped. Can you use generics to inject a certain behavior at runtime.
Matthew Brown

Joined: Apr 06, 2010
Posts: 4542

I suppose it depends on what you're doing with the results.

For a start, you could also make the Context generic, and use the same generic type for your Stuff implementations. That would be suitable for some purposes, but not for others.

If that's no good - what is there in common with the way the context handles the results? If it can potentially do anything with it, I don't see how generics are going to be able to help you much. You can declare myStuff as a Stuff<?>, which would allow you to use any type (and still get type safety within the Stuff classes and maybe in other classes that use them). You might be able to use an upper- or lower-bound (? super Xxx or ? extends Yyy) if there's some common factor to the handling.

Does any of that help?

(By the way, there's another forum that I think this is better suited to, so I'll move it there).
Theodore David Williams
Ranch Hand

Joined: Dec 21, 2009
Posts: 102
I did think about a generic context but I was trying to avoid the user of the api to avoid having to know what type 'Stuff' was. But after you response and a few days of thinking I so do not think that there is any way around it.

Thanks so much for the response. And for moving post!!!
I agree. Here's the link:
subject: Strategy Pattern With Generics
It's not a secret anymore!