Liskov Substitution Principle, 由Barbara Liskov 和 Jeannette Wing在93年提出,其原文为:“Let q(x) be a property provable about objects x of type T. Then q(y) should be true for objects y of type S where S is a subtype of T. ” 。通俗一点来说,LSP的意思是指,“An instance of a class should function as an instance of its superclass” (《Design Pattern Java Workbook》)。
字面上的意思不好理解,举一段程序:
import
java.util.
*
;
public class a{
public static void main(String args[]){
String names[] = { " name1 " , " name2 " };
List L = Arrays.asList(names);
L.add( " name3 " );
}
}
public class a{
public static void main(String args[]){
String names[] = { " name1 " , " name2 " };
List L = Arrays.asList(names);
L.add( " name3 " );
}
}
这段程序运行结果是什么?答案是:
java.lang.UnsupportedOperationException
at java.util.AbstractList.add(Unknown Source)
at java.util.AbstractList.add(Unknown Source)
at a.main(a.java: 7 )
Exception in thread " main "
at java.util.AbstractList.add(Unknown Source)
at java.util.AbstractList.add(Unknown Source)
at a.main(a.java: 7 )
Exception in thread " main "
抛出异常的原因是由 asList() 返回的List不支持add方法。而我们只要把代码改为:
List L
=
new
ArrayList(Arrays.asList(names));
运行就正常了。
我们知道,List, ArrayList, Array 都有一个公共的父类(接口)Collection, asList 最初就是在Collection声明的,所以我们说,这里违反了LSP原则。(当然,从字面上讲,这么说还需要我们把Java接口看成pure的虚类来看)
其实这只是很小的一点,记下备忘