設計原則之里氏代換原則

設計原則之里氏代換原則

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.
    }
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章