设计模式原则(2):里氏替换原则

前端之家收集整理的这篇文章主要介绍了设计模式原则(2):里氏替换原则前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
里氏替换原则:所有引用基类的地方必须能透明地使用其子类的对象。
意思就是说,一个地方引用了父类,程序可以正常运行,如果把引用父类的地方换成子类,这个程序也应该能够正常运行。

例子:
public class Rectangle {
	int width;
	int height;
	public Rectangle(int w,int h){
		width = w;
		height = h;
	}
	public int getArea(){
		return width*height;
	}
}

public class Square extends Rectangle {
	public Square(int w,int h) {
		super(w,h);
	}
	
	public int getArea(){
		return width*width;
	}
}

public class Test {
	public static void main(String[] args) {
		Rectangle rectangle = new Rectangle(10,20);
                // Square rectangle = new  Square(10,20);
		System.out.println("面积:"+rectangle.getArea());
	}
}


如果我们把长方形类Rectangle替换为正方形类Square,那么求出的面积就不正确了,原因是我们继承的时候重写了父类的getArea方法。这是违背里氏替换原则的。
当然,这里只是举个例子,实际项目中我们不会这样修改的。

总结:
1. 尽量不要重写父类方法,而是增加自己特有的方法
2.继承给程序设计带来巨大便利的同时,也带来了弊端。如果一个类被其他的类所继承,则当这个类需要修改时,必须考虑到所有的子类,并且父类修改后,所有涉及到子类的功能都有可能会产生BUG。
原文链接:https://www.f2er.com/javaschema/286339.html

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