Search code examples
javadesign-patternsreflectionproxy-pattern

What is the name of this pattern? (answer: Remote Proxy)


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.


Solution

  • 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.