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);
    }
    }
  • 相关阅读:
    基于边缘保留滤波实现人脸磨皮的算法 | 掘金技术征文
    图像算法---表面模糊算法
    通过人脸照片更换皮肤的方法及系统
    一种数字图像自动祛除斑点的方法
    Leetcode 301.删除无效的括号
    Leetcode 300.最长上升子序列
    Leetcode 299.猜字游戏
    Leetcode 297.二叉树的序列化和反序列化
    Leetcode 295.数据流的中位数
    Leetcode 289.生命游戏
  • 原文地址:https://www.cnblogs.com/o-andy-o/p/10315918.html
Copyright © 2011-2022 走看看