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 以下几 ...
随机推荐
- CSS程序思想
CSS的设计思想,比如:CSS预处理器.CSS对像(OOCSS).SMACSS.Atomic设计和OrganicCSS等 一.CSS预处理器最重要的功能: 1.连接: ...
- Android 学习笔记之Volley开源框架解析(二)
PS:Volley已经学完,可以安心的写一下博客总结一下了... 学习内容: 1.Request的完整封装... 2.RetryPolicy,DefaultRetryPolicy(请求重试策略源码解析 ...
- JS 函数--Date()函数
1.JavaScript没有基本的日期数据类型,所以只能显式的创建Date对象.例如:var myDate=new Date(); 2.为了创建一个存储了特定日期的,或者时间的Date对象,可以简单的 ...
- ADO.NET 连接方式和非链接方式访问数据库
一.//连接方式访问数据库的主要步骤(利用DataReader对象实现数据库连接模式) 1.创建连接对象(连接字符串) SqlConnection con = new SqlConnection(Co ...
- Linq专题之集合初始化器
集合初始化器用来初始化一个集合,和对象初始化器有点类似,都是用一对{}来初始化. using System; using System.Collections.Generic; using Syste ...
- 在IIS7中使用ARR(Application Request Routing)反向代理虚拟目录到Nodejs站点
目标: 1.访问www.arrdemo.com/proxy 跳转到 localhost:8898的Nodejs站点 2.Nodejs站点的页面可以返回到浏览器,包括js,css,图片 3.Nodejs ...
- 【Unity】13.3 Realtime GI示例
分类:Unity.C#.VS2015 创建日期:2016-04-19 一.简介 使用简单示例而不是使用实际示例的好处是能让你快速理解光照贴图和光影效果相关的概念和基本设置办法,这样可避免实际复杂场景中 ...
- 比较偏门的JVM语言Quercus - PHP on JVM
其实,我不确定Quercus是否可以被认定为一门JVM语言:其次Quercus这个东东分开源版与商业版,开源版只能解释执行.而商业版能编译成Java字节码. 但我知道国内,阿里巴巴很早就在使用它,当然 ...
- Gulp-前端进阶A-2
1.js压缩 注意在根目录的package.json文件里在成功安装uglify后要有 "gulp-uglify": "^1.5.4" 才行 var gulp ...
- PFold.js 折叠纸片
PFold.js是一款折叠纸片插件,支持定义折叠纸牌数量.折叠动画效果.折叠方向,而且还支持折叠结束后回调方法. 在线实例 效果一 效果二 效果三 使用方法 <div id="uc-c ...