【发布时间】:2015-02-13 10:32:37
【问题描述】:
假设我有客户端代码使用的接口和具体实现。现在,使用实现该接口的代理模式,我可以通过网络将发出的请求路由到该接口。网络连接当然会失败,这可能会引发异常。
然后,使用该接口的客户端代码会出现意外异常。我猜在这种情况下违反了 LSP 原则。
但是如果不允许网络异常传播到接口之外,在这种情况下如何处理网络异常?
这里有一些 Java 代码来阐明我的意思:
interface Interface
{
abstract void method1();
abstract void method2();
abstract void method3();
}
class Implementation implements Interface
{
void method1();
void method2();
void method3();
}
class ProxyOverNetwork implements Interface
{
// I can't add the NetworkException as it is not part of the Interface
// and would violate LSP, but how to handle the network problems then,
// when the ProxyOverNetwork might not be the right place to do so?
void method1() throws(NetworkException);
void method2() throws(NetworkException);
void method3() throws(NetworkException);
}
我是否必须更改接口以允许异常传播出去?
【问题讨论】:
-
为什么你认为连接失败违反了里氏替换原则?问问自己我们在这里有多少责任?
-
原始接口与网络访问没有任何关系,因此也不会指定抛出任何异常,但使用网络的代理实现会。
-
我认为代理(在幕后)用作依赖项的分发机制在这里让您感到困惑。您可以尝试将其抽象为代理接口的依赖项,然后事情会更清楚。
标签: design-patterns exception-handling liskov-substitution-principle