我刚开始学习软件工程,学习设计模式,总是会聊到设计模式,总是会说高内聚,低耦合,还有依赖注入。什么是依赖,什么是耦合?现在来聊一聊我对于依赖和耦合的理解。
先看下面一段简单代码,
class Apple{private String name = "Apple";}
class People{private List<Apple> stomach = new ArrayList<>();
public void eat(Apple apple){stomach.add(apple);
}
}
class MainDemo {public static void main(String[] args) {People xiaoming= new People();
Apple apple = new Apple();
xiaoming.eat(apple);
}
}
一个人类,一个苹果类,代码的意思是小明吃苹果,保存在胃中。
现在又有一个需求:小明想要去吃香蕉,想要去吃梨子。用上面这一段的代码就不好改了。要完成需求就需要做大量的变化。再加一个 Banana stomach?
这个需求是一个合理的需求,但是因为我们这一段的代码是不合理的,产生了依赖和耦合。
如何减少依赖,就是使用面向接口的编程。依赖一个抽象而不是依赖一个实现。
interface Food{ }
class Banana implement Food{private String name = "Banana";}
class Apple implement Food{private String name = "Apple";}
class People{private List<Apple> stomach = new ArrayList<>();
public void eat(Food food){stomach.add(food);
}
}
class MainDemo {public static void main(String[] args) {People xiaoming= new People();
Food apple = new Apple();
xiaoming.eat(apple);
Food banana = new Banana();
xiaoming.eat(banana);
}
}
这样其实我的接口里面啥也没有,但是却将依赖转移到了抽象的接口。这样我每次添加都可以增加不同水果。其实我这个取名是 Food,那么这个其实可以添加其他的种类食物。这也体现了开放 - 闭合原则。再看最后一个例子
import java.util.*;
interface Food{public String getName();
}
abstract class Fruit implements Food {
protected String type = "fruit";
public abstract void fruitProperty();}
class Banana extends Fruit {
private String name = "Banana";
public String getName(){return name;}
public void fruitProperty(){}
}
class Apple extends Fruit {
private String name = "Apple";
public String getName(){return name;}
public void fruitProperty(){}
}
abstract class Meat implements Food {
protected String type = "meat";
public abstract void meatProperty();}
class Beef extends Meat {
private String name = "Beef";
public String getName(){return name;}
public void meatProperty(){}
}
class Chicken extends Meat {
private String name = "Chicken";
public String getName(){return name;};
public void meatProperty(){}
}
class People{private List<Food> stomach = new ArrayList<>();
public void eat(Food food){stomach.add(food);
}
public void display(){for (Food f : stomach) {System.out.println("stomach have" + f.getName());
}
}
}
class MainDemo {public static void main(String[] args)
{People xiaoming= new People();
Food apple = new Apple();
xiaoming.eat(apple);
Food banana = new Banana();
xiaoming.eat(banana);
Food beef = new Beef ();
xiaoming.eat(beef);
Food chicken = new Chicken ();
xiaoming.eat(chicken);
xiaoming.display();}
}
可以添加任何食物,西瓜,白菜,西兰花。并且他们之间的方法可以是共有的,也可以私有的。当出现几种大类相同的事务,添加一个蔬菜抽象类,这样简化代码。