• 设计模式之依赖倒置原则


    依赖倒置原则(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);
    }
    }
  • 相关阅读:
    设计模式-适配器模式
    设计模式-模板方法模式
    设计模式-策略模式
    spring-消息
    spring-集成redis
    spring-mvc高级技术
    spring-AOP
    restful规范
    十一,装饰器详解
    十,函数对象,嵌套,名称空间与作用域,闭包函数
  • 原文地址:https://www.cnblogs.com/o-andy-o/p/10315918.html
Copyright © 2020-2023  润新知