Consider a class OriginalClass
that might or might not be available on runtime. OriginalClass
has a method doSomething
which should be executed if its class is available.
A way of solving this is creating a class that also has a doSomething
method that calls the OriginalClass.doSomething
using reflection. Something like this:
public class CompatibilityClass {
private static Method originalClass_doSomething = null;
static {
initCompatibility();
};
private static void initCompatibility() {
try {
originalClass_doSomething = Class.forName("originalClass").getMethod("doSomething", new Class[] {});
} catch (NoSuchMethodException nsme) {
} catch (SecurityException se) {
} catch (ClassNotFoundException cnfe) {}
}
public static void doSomething() {
if (originalClass_doSomething != null) {
try {
originalClass_doSomething.invoke(null, new Object[]{});
} catch (Exception e) {}
}
}
}
What is the name of the design pattern applied here? I suspect it's either Adapter , Bridge , Facade or Proxy , but I'm not sure which.
I'd say it's the proxy pattern .
You've create a proxy class that wraps the gory reflection stuff and delegates the method call to a different object.
A proxy, in its most general form, is a class functioning as an interface to something else. The proxy could interface to anything: a network connection, a large object in memory, a file, or some other resource that is expensive or impossible to duplicate.
You pattern is quite similar to something like performing some method call over a network.
Smells like proxy to me. But aren't you better off using Java's default Dynamic Proxy API ?
Definition of proxy:
A proxy forces object method calls to occur indirectly through the proxy object, which acts as a surrogate or delegate for the underlying object being proxied. Proxy objects are usually declared so that the client objects have no indication that they have a proxy object instance.
Simple explanation:
So your code sample looks like a Proxy .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.