Java javapractices (2) - Consider composition instead of subclassing

来源:互联网 发布:mac系统怎么关闭finder 编辑:程序博客网 时间:2024/05/17 02:26

原文:http://www.javapractices.com/topic/TopicAction.do;jsessionid=B58FE8A94F4A053D023EE377EDD85F82?Id=72


把组合当成继承的代替方案



组合:
采用转发调用到某个成员变量
不会对该成员变量的具体实现有依赖
由于可以运行时而不是编译时决定,相对更灵活


继承:
由于和父类或超类的实现紧密耦合,它破坏了封装性。
给父类或超类添加方法会破坏子类
父类或超类会同时添加进来
不同的包可能有不同的人来维护,从不同的包来继承会引入风险




例外的情况是基于模板的设计模式,这种方式下最保险的方式是对抽象基类中的成员都用final修饰,除非有些
需要子类来实现。






All in ALl:
Favor object composition over class inheritance.


...Nevertheless, our experience is that designers overuse inheritance as a reuse technique, and designs are often made more reusable (and simpler) by depending more on object composition. You'll see object composition applied again and again in the design patterns."


(Their first principle, stated earlier in the chapter, is "Program to an interface, not an implementation".) 
0 0
原创粉丝点击