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的更多相关文章

  1. Effective Java 26 Favor generic types

    Use generic types to replace the object declaration Add one or more type parameters to its declarati ...

  2. Effective Java 27 Favor generic methods

    Static utility methods are particularly good candidates for generification. The type parameter list, ...

  3. 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 ...

  4. 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 ...

  5. 《Effective Java》读书笔记 - 4.类和接口

    Chapter 4 Classes and Interfaces Item 13: Minimize the accessibility of classes and members 一个好的模块设计 ...

  6. Effective Java Chapter4 Classes and Interface

    MInimize the accessibility of classes and members 这个叫做所谓的 information hiding ,这么做在于让程序耦合度更低,增加程序的健壮性 ...

  7. Effective Java 目录

    <Effective Java>目录摘抄. 我知道这看起来很糟糕.当下,自己缺少实际操作,只能暂时摘抄下目录.随着,实践的增多,慢慢填充更多的示例. Chapter 2 Creating ...

  8. 【Effective Java】阅读

    Java写了很多年,很惭愧,直到最近才读了这本经典之作<Effective Java>,按自己的理解总结下,有些可能还不够深刻 一.Creating and Destroying Obje ...

  9. 《Effective Java》读书笔记 - 3.对于所有对象都通用的方法

    Chapter 3 Methods Common to All Objects Item 8: Obey the general contract when overriding equals 以下几 ...

随机推荐

  1. n 后问题

    n后问题,解决思路:假设每个皇后占一行(且第i个皇后放在第i - 1 行),依次去尝试下一个皇后该放在该行的哪一列 #include<iostream> #include<cmath ...

  2. Android的Activity生命周期

    Android的Activity就相当于Windows Form中的Form,它的创建和销毁也是有一个生命周期的.主要经过这么7个阶段:   创建Activity:onCreate() 启动Activ ...

  3. SQL SERVER 分布式事务(DTC)

    BEGIN DISTRIBUTED TRANSACTION指定一个由 Microsoft 分布式事务处理协调器 (MS DTC) 管理的 Transact-SQL 分布式事务的起始. 语法BEGIN ...

  4. Enum Helper

    public static class EnumHelper { #region get /// <summary> /// 获得枚举类型所包含的全部项的列表 /// </summa ...

  5. 自定义ConfigurationSection,创建多个嵌套的ConfigurationElementCollection节点

    由于接口地址都是固定的,所以想到使用自定义节点,来将接口都配置到web.config中. 很快,v1.0版本出炉: public class RequestConfigSection : Config ...

  6. 无废话WCF入门教程一[什么是WCF]

    http://www.cnblogs.com/iamlilinfeng/archive/2012/09/25/2700049.html wcf技术交流,同学习共进步,欢迎加群:  群号:3981831 ...

  7. PhpWind 8.7中禁止后台管理员随意修改会员用户名功能

    有人反映PHPWind 8.7中后台可以直接修改用户名的功能太过随意,干脆禁掉. OK,研究一下他的代码,admin/usermange.php  tempalate/admin/usermange. ...

  8. ASP.NET MVC进阶一

    一.控制器相关 在Controller类中方法访问级别为public的方法,就是行为(Action). 如果不希望Controller类中的方法成为Action(可以在地址栏中被访问),有两种实现方式 ...

  9. 泛函编程(21)-泛函数据类型-Monoid

    Monoid是数学范畴理论(category theory)中的一个特殊范畴(category).不过我并没有打算花时间从范畴理论的角度去介绍Monoid,而是希望从一个程序员的角度去分析Monoid ...

  10. Linux命令详解之–ls命令

    今天开始为大家介绍下Linux中常用的命令,首先给大家介绍下Linux中使用频率最高的命令--ls命令. 更多Linux命令详情请看:Linux命令速查手册 linux ls命令用于显示指定工作目录下 ...