设计模式吧 关注:672贴子:1,139
  • 1回复贴,共1

有没有大神?问道题,里氏代换原则的

只看楼主收藏回复

问题2.阅读以下代码,并回答问题:
public class MyOrderedCollection {
protected List<Integer> list = new ArrayList<>();
public void addElement(Integer i) {
list.add(i);
}
public Integer getElement(Integer index) {
return list.get(index);
}
}
public class MyOrderedAndSortedCollection extends MyOrderedCollection {
public void addElement(Integer i) {
super.addElement(i);
Collections.sort(super.list);
}
}
public class LSP1 {
public static void main(String args[]) {
MyOrderedCollection collection1 = new MyOrderedCollection();
MyOrderedCollection collection2 = new MyOrderedAndSortedCollection();
int a = 10, b = 5;
collection1.addElement(a);
collection1.addElement(b);
collection2.addElement(a);
collection2.addElement(b);
PrintSecondElement(collection1);
PrintSecondElement(collection2);
}
public static void PrintSecondElement(MyOrderedCollection collection) {
System.out.println("The second element is :"
+ collection.getElement(1));
}
}
1) 以上代码设计 是否符合里氏代换原则?
2) 若你认为符合,请简要说明理由;若你认为不符合,也请简要说明理由。
问题3. 请简要描述在什么状况下,问题2中的代码会造成麻烦?
问题4. 如果你想避免问题3中出现的麻烦,你会如何修改问题2中的代码设计以使得其遵守里氏代换原则?


IP属地:南非1楼2016-06-10 15:10回复
    我觉得不符合,因为子函数中有个排序,如果代换的话,父函数就发生了改变。但是问题3,4不会。。。


    IP属地:南非2楼2016-06-10 15:14
    回复