zoukankan      html  css  js  c++  java
  • 设计模式之依赖倒置原则

    依赖倒置原则(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,依赖倒置了

    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);
    }
    }
  • 相关阅读:
    WinJS Clipboard
    -ms-grid -ms-grid-rows -ms-grid-row -ms-grid-columns -ms-grid-column
    严格模式 (JavaScript)
    windows rt 扫描二维码
    winmd文件和dll文件的区别
    Windows store 验证你的 URL http:// 和 https:// ms-appx:/// ms-appdata:///local
    使用C#在Windows应用商店程序中获取CPU信息
    python面向对象基础-01
    python红蓝英雄大乱斗(面向对象实现)
    python购物车升级版
  • 原文地址:https://www.cnblogs.com/o-andy-o/p/10315918.html
Copyright © 2011-2022 走看看