設計模式之依賴倒置原則

依賴倒置原則(Dependence Inversion Principle,簡稱DIP)面向接口編程,多態(接口類或者抽象類)

高層模塊不該該依賴低層模塊,兩者都應該依賴其抽象;抽象不該該依賴實現類;實現類應該依賴抽象。 一旦依賴的低層或者具體類改動,則高層可能會須要改動編程

 

錯誤作法: //高層Driver模塊不該該依賴低層DaZhong模塊函數

public class DaZhong {
    public void startup(){
        System.out.println("車子啓動了");
    }
}

//高層Driver模塊不該該依賴低層DaZhong模塊
public class Driver { public void driver(DaZhong vehicle){ vehicle.startup(); } } public class TaskTest { public static void main(String[] args) { Driver driver2 = new Driver(); DaZhong dz2 = new DaZhong(); driver2.driver(dz2); } }

 

 

正確作法:抽象IDriver依賴抽象IVehicle;具體的DaZhongVehicle依賴於抽象IVehicle,依賴倒置了this

public interface IDriver {
    //接口聲明依賴對象,接口注入IVehicle,抽象IDriver依賴抽象IVehicle
    void driver(IVehicle vehicle);
}

public class BaoMaDriver implements IDriver {
    IVehicle vehicle;

    //構造函數注入,DaZhongVehicle依賴IVehicle
    public  BaoMaDriver(IVehicle vehicle) {
        this.vehicle = vehicle;
    }
        public BaoMaDriver(){}

    public void driver(IVehicle vehicle) {
        vehicle.startup();
    }

    //set方法注入,DaZhongVehicle依賴IVehicle
    public void setVehicle(IVehicle vehicle) {
        this.vehicle = vehicle;
    }

}


public interface IVehicle {
    void startup();
}


public class DaZhongVehicle implements IVehicle {
    public void startup() {
        System.out.println("大衆啓動了");
    }

}

public class TaskTest {
    public static void main(String[] args) {
        IDriver driver = new BaoMaDriver();
        IVehicle dz = new DaZhongVehicle();
//這裏變成了DaZhongVehicle依賴IVehicle,具體依賴於抽象,依賴倒置了
        driver.driver(dz);     } }
相關文章
相關標籤/搜索