Dependence Inversion Principle 依赖倒置原则
简介
定义:高层模块不应该依赖底层模块,二者都应该依赖其抽象
主要核心思想
强调抽象不应该依赖细节;细节应该依赖抽象,及针对接口编程,不要针对实现编程
优点
可以减少类间的耦合性、提高系统稳定性提高代码可读性和可维护性可降低修改程序所造成的风险实践案例
手机为例:618活动中Aaron购买了多部品牌手机
public interface IPhone {void buy();}
public class XiaoMiPhone implements IPhone{@Overridepublic void buy() {System.out.println("Aaron购买了一部小米手机");}}public class HuaWeiPhone implements IPhone{@Overridepublic void buy() {System.out.println("Aaron购买了一部华为手机");}}public class ApplePhone implements IPhone {@Overridepublic void buy() {System.out.println("Aaron购买了一部苹果手机");}}
public class Aaron {IPhone iPhone;// public Aaron(IPhone iPhone) {// this.iPhone = iPhone;// }// ====== V1 =====// public void buyXiaoMiPhone(){// System.out.println("Aaron购买了一部小米手机");// }//// public void buyHuaWeiPhone(){// System.out.println("Aaron购买了一部华为手机");// }//// public void buyApplePhone(){// System.out.println("Aaron购买了一部苹果手机");// }// ====== V2 =====// public void buy(IPhone iPhone){// iPhone.buy();// }public void setiPhone(IPhone iPhone) {this.iPhone = iPhone;}// ====== V3/4 =====public void buy(){iPhone.buy();}}
public class PhoneTest {public static void main(String[] args) {// ======= V1 ========// Aaron aaron = new Aaron();// aaron.buyXiaoMiPhone();// aaron.buyHuaWeiPhone();// aaron.buyApplePhone();// ======= V2 ========// Aaron aaron = new Aaron();// aaron.buy(new XiaoMiPhone());// ======= V3 ========// Aaron aaron = new Aaron(new XiaoMiPhone());// aaron.buy();// ======= V4 ========Aaron aaron = new Aaron();aaron.setiPhone(new XiaoMiPhone());aaron.buy();}}