依赖倒置原则

来源:互联网 发布:淘宝正道体育 编辑:程序博客网 时间:2024/06/07 18:21
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
原创粉丝点击