是不是一個好的程式有兩個指標可以判斷是否為高凝聚性,是否為低相依性。
Higher cohesion(高凝聚性)想表達的其實就是事物凝聚的狀態或程度。
Looser coupling(低相依性)想表達的是程式單元之間牽連相依的程度,模組之間的相依性越寬鬆愈好。
範例:
public interface Car {//car 介面
public void travelByCar();//定義抽象方法給下面介面實作
}
public class CarBMW implements Car {//實作car介面
public void travelByCar() {
System.out.println("BMW寶馬-汽車旅遊");
}
}
public class CarBenz implements Car {
public void travelByCar() {
System.out.println("Benz賓士-汽車旅遊");
}
}
public class TravelBusiness {
private Car car;
//定義一個物件參考變數car,事實上在被setCar指派new的物件之後等於 Car car = new CarBenz() 或 Car car = new CarBMW(),是為了要從car interface借過到CarBenz 或CarBMW
public void setCar(Car car) {//將new CarBez() 或 new CarBMW()參考到上面的Car car
this.car = car;
}
public Car getCar() {
return car;
}
public void travel() {
if(car == null) {
throw new RuntimeException("未輸入汽車種類...");
}
car.travelByCar();//經由上面car介面借過到下面new CarBez() 或 new CarBMW()的travelByCar()方法
}
}
public class TravelBusinessTest {
public static void main(String[] args) {
TravelBusiness business1 = new TravelBusiness();//new一個TravelBusiness物件business1作為各類車輛的容器
business1.setCar(new CarBenz());//new一個CarBenz物件並將這個物件,設定TravelBusiness裡的變數
business1.travel();//使用個TravelBusiness物件的travel()方法
TravelBusiness business2 = new TravelBusiness();
business2.setCar(new CarBMW());
business2.travel();
}
}