Dependency Inversion Principle(英文名,装逼用的)
不能让高层的组件依赖于低层的组件,且无论高层与低层组件,两者都应该依赖于抽象。
例:
- class Pizza{
- public String taste(){
- return "香浓的芝士味";
- }
- }
- class Customer{
- public void eat(Pizza pizza){
- System.out.println("顾客开始吃东西");
- System.out.println(pizza.taste());
- }
- }
- public class Client{
- public static void main(String[] args){
- Customer cust= new Customer();
- cust.eat(new Pizza());
- }
- }
- class Hamburger{
- public String taste(){
- return "厚厚的肉饼";
- }
- }
这是因为Pizza和Customer的耦合度太高了,所以导致顾客只能吃披萨!这是一件多么傻逼的事儿!
因此我们需要改变一下这个情况,让他们都依赖于Food接口。
于是代码变成了这个样子:
- class Pizza implements Food{
- @overide
- public String taste(){
- return "香浓的芝士味";
- }
- }
- class Hamburger implements Food{
- @overide
- public String taste(){
- return "厚厚的肉饼";
- }
- }
Interface Food(){
public String taste();
}
- class Customer{
- public void eat(Food food){
- System.out.println("顾客开始吃东西");
- System.out.println(food.taste());
- }
- }
- public class Client{
- public static void main(String[] args){
- Customer cust= new Customer();
- cust.eat(new Pizza());
- cust.eat(new Hamburger());
- }
- }
将来如果添加其他的食物,就将该食物实现Food接口,此时即可极大的降低代码的耦合度。这也是所谓的依赖倒置原则。