[英]What is the name of this pattern? (answer: Remote Proxy)
Consider a class OriginalClass
that might or might not be available on runtime. 考虑一个在运行时可能可用或可能不可用的类
OriginalClass
。 OriginalClass
has a method doSomething
which should be executed if its class is available. OriginalClass
具有doSomething
方法,如果其类可用,则应执行该方法。
A way of solving this is creating a class that also has a doSomething
method that calls the OriginalClass.doSomething
using reflection. 解决此问题的一种方法是创建一个类,该类也具有
doSomething
方法,该方法使用反射来调用OriginalClass.doSomething
。 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.
我怀疑它是Adapter , Bridge , Facade或Proxy ,但是我不确定是哪个。
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 ?
但是,使用Java的默认动态代理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 . 因此,您的代码示例看起来像Proxy 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.