这个图案的名字是什么? (答案:远程代理)
考虑一个类OriginalClass
,它在运行时可能可用,也可能不可用。 OriginalClass
有一个 doSomething
方法,如果其类可用,则应执行该方法。
解决此问题的一种方法是创建一个类,该类还具有使用反射调用 OriginalClass.doSomething
的 doSomething
方法。像这样:
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) {}
}
}
}
这里应用的设计模式的名称是什么?我怀疑它是适配器、桥、外观或代理,但我不确定是哪一个。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我想说这是代理模式。
您已经创建了一个代理类,它包装了血淋淋的反射内容并将方法调用委托给不同的对象。
您的模式非常类似于通过网络。
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.
You pattern is quite similar to something like performing some method call over a network.
对我来说闻起来像代理。但是使用 Java 的默认动态代理 API 不是更好吗?
代理的定义:
Smells like proxy to me. But aren't you better off using Java's default Dynamic Proxy API?
Definition of proxy:
简单解释:
所以您的代码示例看起来像一个代理。
Simple explanation:
So your code sample looks like a Proxy.