里氏替换原则(Liskov Substitution Principle LSP)

前端之家收集整理的这篇文章主要介绍了里氏替换原则(Liskov Substitution Principle LSP)前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

Liskov于1987年提出了一个关于继承的原则“Inheritance should ensure that any property proved about supertype objects also holds for subtype objects.”——“继承必须确保超类所拥有的性质在子类中仍然成立。”也就是说,当一个子类的实例应该能够替换任何其超类的实例时,它们之间才具有is-A关系。

  1. public abstract class AbstractBird {
  2.  
  3. protected String color;
  4. protected String name;
  5.  
  6. public AbstractBird(String color,String name) {
  7. this.color = color;
  8. this.name = name;
  9. }
  10.  
  11. public void show() {
  12. System.out.println("看那是" + this.name + ":颜色是" + this.color);
  13. drinking();
  14. goWalk();
  15. sleep();
  16. }
  17.  
  18. public abstract void goWalk();
  19.  
  20. public abstract void sleep();
  21.  
  22. public abstract void drinking();
  23. }
  24.  
  25. public class Zoo {
  26.  
  27. private AbstractBird abstractBird;
  28.  
  29. public Zoo(AbstractBird abstractBird) {
  30. this.abstractBird = abstractBird;
  31. }
  32.  
  33. public void show() {
  34. this.abstractBird.drinking();
  35. }
  36. }
  37. public static void main(String[] args) {
  38. // Zoo zoo = new Zoo(new Canary("红色","金丝雀"));
  39. Zoo zoo = new Zoo(new Magpie("蓝色","喜鹊"));
  40. // Zoo zoo = new Zoo(new Sparrow("黑色","麻雀"));
  41. zoo.show();

对象本身有一套对自身状态进行校验的检查条件,以确保该对象的本质不发生改变,这称之为不变式(Invariant)。

  1. public class Stone {
  2.  
  3. public Number getNumber() {
  4. return new Integer(99);
  5. }
  6. }
  7.  
  8. public class Adamas extends Stone {
  9.  
  10. @Override
  11. public Integer getNumber(){
  12. return new Integer(22);
  13. }
  14. }
  15. public class StoneClient {
  16.  
  17. public static void main(String[] args) {
  18. Stone stone = new Adamas();
  19. System.out.println(stone.getNumber());
  20. }
  21. }
  22. 答案
  23. 22
  24.  
  25. 如果把父类的参数缩小,子类的参数扩大,就问题出问题
  26.  
  27. public class Stone {
  28.  
  29. public Number getNumber(HashMap map) {
  30. return new Integer(99);
  31. }
  32. }
  33. public class Adamas extends Stone {
  34.  
  35. public Number getNumber(Map map) {
  36. return new Integer(22);
  37. }
  38. }
  39. public class StoneClient {
  40.  
  41. public static void main(String[] args) {
  42. //Stone stone = new Stone();
  43. Adamas stone = new Adamas();
  44. System.out.println(stone.getNumber(new HashMap()));
  45. }
  46. }
  47. 答案 2个打印出都是99 ,我们想要的,9922

总结就是子类的方法参数一定要小于等于父类的参数。

猜你在找的设计模式相关文章