开发者

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 app开发者_Go百科lied 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:

  • Adapter: when you have two classes (A and B) that are semantically equivalent/similar, but have different interfaces. Adapter implements interface of A but delegates to B or vice-versa so A and B can be used interchangeably
  • Bridge - typically used with whole inheritance tree (I never used it though)
  • Facade - hide complexity of one or more classes behind simpler interface
  • Proxy - same interface as the target object, delegating to it, typically used for lazy loading and decoupling from target.

So your code sample looks like a Proxy.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜