This week's book giveaway is in the Mac OS forum. We're giving away four copies of a choice of "Take Control of Upgrading to Yosemite" or "Take Control of Automating Your Mac" and have Joe Kissell on-line! See this thread for details.
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.
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
Joined: Dec 21, 2009
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!!!