I have a Java class that can extend either of two third-party classes, which I cannot change. I can choose either of these implementations at compile time with no changes to my class other than the "extends" declaration. Unfortunately I need to choose which implementation to use at runtime, not at compile time. What's the best way to select between these two implementations at run-time without duplicating the entire derived class?
+3
A:
It sounds like you require a Strategy pattern.
the strategy pattern (also known as the policy pattern) is a particular software design pattern, whereby algorithms can be selected at runtime.
So your Java class should contain a reference to one of the two classes that you want to use, and bridge to that implementation. The implementation you choose can be selected at runtime. It's not clear from your problem description, but if your two 3rd-party classes implement a common interface, then your Java class would most likely implement this interface and you can directly map to the referenced 3rd-party class.
Brian Agnew
2010-10-07 23:00:41