最小知識(shí)原則万牺,Principle of Least Knowledge
這個(gè)原則告訴我們罗珍,在方法中,只能調(diào)用以下對(duì)象的方法:
1脚粟、對(duì)象本身
2覆旱、作為參數(shù)傳遞給此方法的對(duì)象
3、在此方法中創(chuàng)建的對(duì)象
4核无、對(duì)象的組件
下面這個(gè)例子扣唱,注釋分別對(duì)應(yīng)上面的標(biāo)號(hào)對(duì)象
public class car {
? ? Engine engine;
? ? public void start(Key key){
? ? ? ? Doors door = new Doors();
? ? ? ? boolean authorized = key.turns();? ?// 2
? ? ? ? if(authorized){
? ? ? ? ? ? engine.start();? ? ? ? ? ? ? ? ? ? ? ? ? ? ?// 4
? ? ? ? ? ? updateDashboardDisplay();? ? ? ? // 1
? ? ? ? ? ? doors.lock();? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? // 3
????????}
????}
? ? public void updateDashboardDisplay(){? ? ? ?
? ? }
}
注意:不要調(diào)用其他方法返回的對(duì)象的方法。
/**
* 不符合最小知識(shí)原則
*/
public House {
? ? WeatherStation station;
? ? public float getTemp() {
? ? ? ? return station.getThermometer().getTemperature();
????}
}
/**
*? 符合最小知識(shí)原則
*/
public House() {
? ? WeatherStation station;
? ? public float getTemp() {
? ? ? ? Thermometer thermometer = station.getThermometer();
? ? ? ? return getTempHelper(thermometer);
????}
? ? public float getTempHelper(Thermometer thermometer?) {
? ? ? ? return thermometer.getTemperature();
????}
}
最小知識(shí)原則的利弊
利:減少對(duì)象之間的依賴,維護(hù)性提高
弊:增加類的復(fù)雜度和開發(fā)時(shí)間画舌,降低運(yùn)行效率