合成复用原则
原则是尽量使用合成/聚合的方式而不是继承
继承具有侵入性,耦合性增强
代码描述
/**
* @author huangqh
* @create 2020/9/8 12:51
*/
public class composite {
public static void main(String[] args) {
new E().q.operation1();
new R().q.operation1();
new Y().operation1();
}
}
class Q{
public void operation1(){
}
public void operation2(){
}
}
class W{
//依赖
public void opreation1(Q q){
q.operation1();
}
}
class E{
//聚合
Q q;
public void setQ(Q q) {
this.q = q;
}
}
class R{
//组合
Q q = new Q();
}
//继承
class Y extends Q{
}
设计原则的核心思想
找到应用中可能需要变化的地方,独立出来,将不需要变化的地方放在一起
针对接口编程,而不是针对实现编程
为了交互对象之间的松耦合设计而努力