Effective Java 16 Favor composition over inheritance
Inheritance disadvantage
Unlike method invocation, inheritance violates encapsulation. Since you don't know the super class implementation which may involve some unpredictable calling between different methods of super class. And it is difficult to maintain the subclass when there is a change of the super class.
Be careful with the interaction between inner methods of the superclass. Here is the demo.
package com.effectivejava.classinterface;
import java.util.Collection;
import java.util.Set;
/**
* @author Kaibo
*
*/
// Wrapper class - uses composition in place of inheritance
public class InstrumentedSet<E> extends ForwardingSet<E> {
private int addCount = 0;
public InstrumentedSet(Set<E> s) {
super(s);
}
@Override
public boolean add(E e) {
addCount++;
return super.add(e);
}
@Override
public boolean addAll(Collection<? extends E> c) {
addCount += c.size();
return super.addAll(c);
}
public int getAddCount() {
/* If you directly extends one implementation such as HashSet<E> of the Set<E> interface you will get the wrong addCount since the addAll method invoke the add method internally which has been override by your sub class.
*/
return addCount;
}
}
/**
* Implementation of prefer to composite to inherence.
*/
package com.effectivejava.classinterface;
import java.util.Collection;
import java.util.Iterator;
import java.util.Set;
/**
* @author Kaibo
*
*/
// Reusable forwarding class
public class ForwardingSet<E> implements Set<E> {
private final Set<E> s;
public ForwardingSet(Set<E> s) {
this.s = s;
}
public void clear() {
s.clear();
}
public boolean contains(Object o) {
return s.contains(o);
}
public boolean isEmpty() {
return s.isEmpty();
}
public int size() {
return s.size();
}
public Iterator<E> iterator() {
return s.iterator();
}
public boolean add(E e) {
return s.add(e);
}
public boolean remove(Object o) {
return s.remove(o);
}
public boolean containsAll(Collection<?> c) {
return s.containsAll(c);
}
public boolean addAll(Collection<? extends E> c) {
return s.addAll(c);
}
public boolean removeAll(Collection<?> c) {
return s.removeAll(c);
}
public boolean retainAll(Collection<?> c) {
return s.retainAll(c);
}
public Object[] toArray() {
return s.toArray();
}
public <T> T[] toArray(T[] a) {
return s.toArray(a);
}
@Override
public boolean equals(Object o) {
return s.equals(o);
}
@Override
public int hashCode() {
return s.hashCode();
}
@Override
public String toString() {
return s.toString();
}
}
Wrapper class (Composite) disadvantage
Wrapper classes are not suited for use in callback frameworks, wherein objects pass self-references to other objects for subsequent invocations ("callbacks").
To avoid the method invoke subclass's overrided version
You can eliminate a class's self-use of overridable methods mechanically, without changing its behavior. Move the body of each overridable method to a private "helper method" and have each overridable method invoke its private helper method. Then replace each self-use of an overridable method with a direct invocation of the overridable method's private helper method.
Effective Java 16 Favor composition over inheritance的更多相关文章
- Effective Java 26 Favor generic types
Use generic types to replace the object declaration Add one or more type parameters to its declarati ...
- Effective Java 27 Favor generic methods
Static utility methods are particularly good candidates for generification. The type parameter list, ...
- Effective Java 60 Favor the use of standard exceptions
Benefits to reuse preexisting exceptions It makes your API easier to learn and use. Programs using y ...
- Effective Java Index
Hi guys, I am happy to tell you that I am moving to the open source world. And Java is the 1st langu ...
- 《Effective Java》读书笔记 - 4.类和接口
Chapter 4 Classes and Interfaces Item 13: Minimize the accessibility of classes and members 一个好的模块设计 ...
- Effective Java Chapter4 Classes and Interface
MInimize the accessibility of classes and members 这个叫做所谓的 information hiding ,这么做在于让程序耦合度更低,增加程序的健壮性 ...
- Effective Java 目录
<Effective Java>目录摘抄. 我知道这看起来很糟糕.当下,自己缺少实际操作,只能暂时摘抄下目录.随着,实践的增多,慢慢填充更多的示例. Chapter 2 Creating ...
- 【Effective Java】阅读
Java写了很多年,很惭愧,直到最近才读了这本经典之作<Effective Java>,按自己的理解总结下,有些可能还不够深刻 一.Creating and Destroying Obje ...
- 《Effective Java》读书笔记 - 3.对于所有对象都通用的方法
Chapter 3 Methods Common to All Objects Item 8: Obey the general contract when overriding equals 以下几 ...
随机推荐
- AutoTransformHandler
public static ObservableCollection<F> Transform<T, F>(List<T> target) where F : ne ...
- 【C#】线程之Parallel
在一些常见的编程情形中,使用任务也许能提升性能.为了简化变成,静态类System.Threading.Tasks.Parallel封装了这些常见的情形,它内部使用Task对象. Parallel.Fo ...
- win 10 远程连接出现 "由于安全设置错误, 客户端无法连接到远程计算机. 确定你已登录到网络后.” 错误
win 10 远程连接出现 "由于安全设置错误, 客户端无法连接到远程计算机. 确定你已登录到网络后.” 错误 解决方法如下: Step 1:打开"本地安全策略"- Wi ...
- 关于 hangfire 的权限问题
hangfire 是一个分布式后台执行服务. 官网:http://hangfire.io/ 我看中hangfire的地方是 1:使用简单 2:多种持久化保存方案.支持sqlserver ,msmq等 ...
- knockout的依赖属性dependentObservable的参数 和Value转换器
可写的依赖监控属性ko.dependentObservable的参数 read: 必选,一个用来执行取得依赖监控属性当前值的函数write: 可选,如果声明将使你的依赖属性可写,别的代码如果这个 ...
- 不可或缺 Windows Native (3) - C 语言: 运算符,表达式,条件语句,循环语句,转向语句,空语句等
[源码下载] 不可或缺 Windows Native (3) - C 语言: 运算符,表达式,条件语句,循环语句,转向语句,空语句等 作者:webabcd 介绍不可或缺 Windows Native ...
- 重新想象 Windows 8 Store Apps (43) - 多线程之任务: Task 基础, 多任务并行执行, 并行运算(Parallel)
[源码下载] 重新想象 Windows 8 Store Apps (43) - 多线程之任务: Task 基础, 多任务并行执行, 并行运算(Parallel) 作者:webabcd 介绍重新想象 W ...
- 回文串---Hotaru's problem
HDU 5371 Description Hotaru Ichijou recently is addicated to math problems. Now she is playing wit ...
- .Net开发人员有趣的Podcast
如果你是一个.Net开发人员,那么一定不要错过这些Podcasts,它们可是即可以了解IT业态,又可以锻炼英文听力.有采访很多开源人员,涉及项目等等.先尽力听他们说什么,然后再看Tra ...
- 我所了解的WEB开发(3) - 彩虹的颜色
据说彩虹有七彩颜色,从外至内分别为:红.橙.黄.绿.青.蓝.紫.这些我倒是没有验证过,但是学生时代就不止一次色盲检测,还是让我足够确信对颜色的分辨应该和大多数人相似的. 还听说大多数哺乳动物是色盲.如 ...