依赖倒置原则

Dependency Inversion Principle(英文名,装逼用的)

不能让高层的组件依赖于低层的组件,且无论高层与低层组件,两者都应该依赖于抽象。
例:
  1. class Pizza{  
  2.     public String taste(){  
  3.         return "香浓的芝士味";  
  4.     }  
  5. }  
  6.   
  7. class Customer{  
  8.     public void eat(Pizza pizza){  
  9.         System.out.println("顾客开始吃东西");  
  10.         System.out.println(pizza.taste());  
  11.     }  
  12. }  
  13.   
  14. public class Client{  
  15.     public static void main(String[] args){  
  16.         Customer custnew Customer();  
  17.         cust.eat(new Pizza());  
  18.     }  
  19. }  
此时,身为顾客,只能吃披萨,当为其创建一个披萨,顾客就开始吃披萨了。然而现在披萨没了,让顾客换吃汉堡,顾客便没法吃了。
  1. class Hamburger{  
  2.     public String taste(){  
  3.         return "厚厚的肉饼";  
  4.     }  
  5. }  
因为eat方法中,只能接受Pizza而不能接受Hamburger。
这是因为Pizza和Customer的耦合度太高了,所以导致顾客只能吃披萨!这是一件多么傻逼的事儿!
因此我们需要改变一下这个情况,让他们都依赖于Food接口。
于是代码变成了这个样子:
  1. class Pizza implements Food{  
  2. @overide
  3.     public String taste(){  
  4.         return "香浓的芝士味";  
  5.     }  
  6. }                                   
  7. class Hamburger implements Food{ 
  8. @overide
  9.      public String taste(){ 
  10.         return "厚厚的肉饼";   
  11.     }
  12.  }
          Interface Food(){
          public String taste();
         }
  1.   
  2. class Customer{  
  3.     public void eat(Food food){  
  4.         System.out.println("顾客开始吃东西");  
  5.         System.out.println(food.taste());  
  6.     }  
  7. }   

  8.   
  9. public class Client{  
  10.     public static void main(String[] args){  
  11.         Customer custnew Customer();  
  12.         cust.eat(new Pizza());  
  13.         cust.eat(new Hamburger());
  14.     }  
  15. }  
将来如果添加其他的食物,就将该食物实现Food接口,此时即可极大的降低代码的耦合度。这也是所谓的依赖倒置原则。


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值