假设我有一个FooInterface具有以下签名的接口:
interface FooInterface {
public function doSomething(SomethingInterface something);
}
还有一个ConcreteFoo实现该接口的具体类:
class ConcreteFoo implements FooInterface {
public function doSomething(SomethingInterface something) {
}
}
ConcreteFoo::doSomething()如果它传递了一种特殊类型的SomethingInterface对象(例如称为SpecialSomething),我想做一些独特的事情。
如果我加强方法的先决条件或引发新的异常,则绝对是LSP违规,但是如果我SpecialSomething在为通用SomethingInterface对象提供后备时又对特殊情况的对象进行了处理,这是否仍会违反LSP ?就像是:
class ConcreteFoo implements FooInterface {
public function doSomething(SomethingInterface something) {
if (something instanceof SpecialSomething) {
// Do SpecialSomething magic
}
else {
// Do generic SomethingInterface magic
}
}
}
doSomething()方法的目的是将类型转换为SpecialSomething:如果接收到该方法SpecialSomething,则只会返回未修改的对象,而如果接收到一个通用SomethingInterface对象,则将运行算法将其转换为SpecialSomething对象。由于前提条件和后置条件保持不变,因此我认为合同没有受到违反。