設(shè)計(jì)原則(二)接口隔離

接口隔離原則有兩種定義:

第一種定義: Clients should not be forced to depend upon interfaces that they don't use.
客戶端不應(yīng)該依賴它不需用的接口。

第二種定義:The dependency of one class to another one should depend on the smallest possible interface。類間的依賴關(guān)系應(yīng)該建立在最小的接口上。

簡單來說就是有兩種車,普通汽車和電動車,普通汽車加油,電動車充電。
這個時候如果我們?yōu)閮煞N車抽象一個接口ICar.在接口中定義加油和充電兩種補(bǔ)給方法.
如圖:


image.png

從圖中看出,NormalCar其實(shí)是不需要charge方法的,但是因?yàn)閷?shí)現(xiàn)了ICar接口,使得NormalCar不得不實(shí)現(xiàn)charge方法,即被迫實(shí)現(xiàn)了不需要的方法。
同理,ElectricCar也不需要refuel方法。
從中可以看出,該設(shè)計(jì)就是違反ISP的設(shè)計(jì)。
我們試著修改成如下UML:


image.png

普通車和電動車,各實(shí)現(xiàn)自己的接口。這樣就不需要被迫實(shí)現(xiàn)對自己沒用的方法了.
如果這個時候又來一種混動車,應(yīng)該怎么處理呢?
只要分別實(shí)現(xiàn)汽油車接口和電動車接口就OK了.
如圖:
image.png

代碼如下:

/**
 * 汽油車接口
 * @author saisaimayi
 *
 */
public interface IGasCar {

    public void refuel();
}

/**
 * 電動車接口
 * @author saisaimayi
 *
 */
public interface IElectricCar {

    public void charge();
}

/**
 * 普通車
 * @author saisaimayi
 *
 */
public class NormalCar implements IGasCar {

    public void refuel() {
        System.out.println("reruel for normal car...");
        
    }

}

 /**
 * 電動車類
 * @author saisaimayi
 *
 */
public class ElectricCar implements IElectricCar {

    public void charge() {
        System.out.println("charge for Electric car...");
        
    }

}

/**
 * 混動車類
 * @author saisaimayi
 *
 */
public class HybridCar implements IGasCar, IElectricCar {

    public void charge() {
        System.out.println("charge for hybrid car...");

    }

    public void refuel() {
        System.out.println("refuel for hybrid car...");

    }

}

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容