Java javapractices (2) - Consider composition instead of subclassing

原文: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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值