最少知识原则

2014-11-24 11:03:53 · 作者: · 浏览: 0

一句话:不要让太多类耦合在一起,以免形成依赖,不易于维护和理解。


原则上只应调用:

1 该对象本身

2 被当作方法的参数而传递进来的对象

3 此放发所创建或实例化的任何对象

4 对象的任何组件

例:

不采用原则:


[java] public float getValue(){
B b = a.getB();
b.getValue();
}

public float getValue(){
B b = a.getB();
b.getValue();
}
采用原则


[java] public float getValue(){
a.getBValue();
}

public float getValue(){
a.getBValue();
}
清楚的看到违反原则的与B有了耦合,而遵守原则的则完全与B解藕。

自己总结:

优点:定义所说解藕易维护

缺点:无法使用成员对象本身方法须在交互类封装