设计原则之里氏代换原则 substitute = replace 替换 sub 下 st石头 i我 tu土 te特别 我用石头替换下土,造了特比坚固的房子 hierarchy [‘harɑk] = level 等级 hi海豹 er儿子 ar are是 ch成龙 海豹儿子的雷霆战机等级是比成龙高 derive [di‘raiv] 起源,派生 de德国 rive river河 德国的莱茵河起源于阿尔卑斯山 动机: 当我们创建类的层级(继承),我们继承一些类,创建一些派生类。我们必须确保新的派生类只是继承而不是代替父类的方法。否则子类可能产生意想不到的影响当它们被使用的时候。 结论: 里氏替换原则是开闭原则的扩展,它意味着我们要确保子类继承父类的时候不要改变父类的行为。 Example: 当正方形类继承矩形类,setWidth()和setHeight()会产生误解 // Violation of Likov‘s Substitution Principle class Rectangle { protected int m_width; protected int m_height; public void setWidth(int width){ m_width = width; } public void setHeight(int height){ m_height = height; } public int getWidth(){ return m_width; } public int getHeight(){ return m_height; } public int getArea(){ return m_width * m_height; } } class Square extends Rectangle { public void setWidth(int width){ m_width = width; m_height = width; } public void setHeight(int height){ m_width = height; m_height = height; } } class LspTest { private static Rectangle getNewRectangle() { // it can be an object returned by some factory ... return new Square(); } public static void main (String args[]) { Rectangle r = LspTest.getNewRectangle(); r.setWidth(5); r.setHeight(10); // user knows that r it‘s a rectangle. // It assumes that he‘s able to set the width and height as for the base class System.out.println(r.getArea()); // now he‘s surprised to see that the area is 100 instead of 50. } }
时间: 2024-10-25 08:26:24