设计模式原则之最小知识原则

2018-09-12  本文已影响0人  悠然望剑

最小知识原则,Principle of Least Knowledge

这个原则告诉我们,在方法中,只能调用以下对象的方法:

1、对象本身

2、作为参数传递给此方法的对象

3、在此方法中创建的对象

4、对象的组件

下面这个例子,注释分别对应上面的标号对象

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(){       

    }

}

注意:不要调用其他方法返回的对象的方法。

/**

* 不符合最小知识原则

*/

public House {

    WeatherStation station;

    public float getTemp() {

        return station.getThermometer().getTemperature();

    }

}

/**

*  符合最小知识原则

*/

public House() {

    WeatherStation station;

    public float getTemp() {

        Thermometer thermometer = station.getThermometer();

        return getTempHelper(thermometer);

    }

    public float getTempHelper(Thermometer thermometer ) {

        return thermometer.getTemperature();

    }

}

最小知识原则的利弊

利:减少对象之间的依赖,维护性提高

弊:增加类的复杂度和开发时间,降低运行效率

上一篇 下一篇

猜你喜欢

热点阅读