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 以下几 ...
随机推荐
- python 在sublime 中的配置
首先可以先装package control 方法——按ctrl+`,然后在命令行里复制粘贴以下代码, import urllib2,os;pf='Package Control.sublime-pac ...
- ASP.NET MVC5--为数据库新增字段(涉及数据库迁移技术)
Setting up Code First Migrations for Model Changes--为模型更改做数据库迁移. 1.打开资源管理器,在App_Data文件夹下,找到movies.md ...
- C#中Guid类型值如何判断不是初始值!
示例: public Guid _CurrentApplayInfoID { get; set; } 如何判断不是初始值"00000000-0000-0000-0000-0000000000 ...
- WinForm输入网址打开源码
无聊练习一下WinForm,输入网址,点击按钮就在浏览器打开网址. 源代码下载: http://hovertree.com/h/bjaf/cao15h74.htm
- 自定义动画方法animate
animate的使用方法:animate(params,speed,callback); 例子:animate({ right: "-=600px",height:"+= ...
- 004_URL 路由 - URL 路由
在Web Form 情况下,每一个 ASPX页面既是一个文件,又是一个队请求自包含的响应.而在 MVC 情况下,请求是由控制器类中的动作方法处理的,而且与硬盘上的文件没有一对一的相互关系. ASP.N ...
- No.003:Longest Substring Without Repeating Characters
问题: Given a string, find the length of the longest substring without repeating characters.Example:Gi ...
- IE Unknown runtime error
1. 在函数中使用原生的js的时候,有时在IE下会出现Unknown runtime error 火狐下正常 2. 解决办法, 将原生js改成jquery处理兼容问题 document.getElem ...
- jquery function Optional Arguments
1.javascript 选项散列对象 function Test(p1,p2,p3,p4,p5){ //do something } call: 参数可选 Test({ p1:value1, p2: ...
- 初学者对WAMP服务器的设置
服务器设置 在wamp/bin/apache/Apache###/conf/httpd.conf文件中设置 根文件夹 修改documentroot和directory两项 保存后重启服务 404返回值 ...