第18条:接口优于抽象类

1、接口是定义mixin(混合类型)的理想选择。

2、接口允许我们构造非层次结构的类型框架。

比如:

public interface Singer {
AudioClip sing(Song s);
}
public interface Songwriter {
Song compose(boolean hit);
}
定义两个接口,一个表示歌唱家,另一个表示作曲家。

显示生活中,存在一个人既是歌唱家又是作曲家的情况。由于java只支持类的单继承,使用类层次定义的话很难实现,要实现的话也需要一个十分庞大的类层次关系,容易产生“组合爆炸”现象。

而实用接口实现就很简单,代码如下:

public interface SingerSongwriter extends Singer, Songwriter {
 AudioClip strum();
 void actSensitive();
}

3、骨架实现类:就是实现了接口的抽象类。骨架实现类结合了接口和抽象类的优点,骨架类中可以有一些接口方法的实现,也可以有接口中的抽象(abstract)方法。

下面是一个骨架类的使用代码:

static List<Integer> intArrayAsList(final int[] a) {
if (a == null)
throw new NullPointerException();
return new AbstractList<Integer>() {
public Integer get(int i) {
return a[i]; // Autoboxing (Item 5)
}
@Override public Integer set(int i, Integer val) {
int oldVal = a[i];
a[i] = val; // Auto-unboxing
return oldVal; // Autoboxing
}
public int size() {
return a.length;
}
};
}
返回一个匿名类对象。而这个匿名类对象的类AbstractList就是被定义为一个骨架类。

下面也是一个骨架类的代码:

public abstract class AbstractMapEntry<K,V>
implements Map.Entry<K,V> {
// Primitive operations
public abstract K getKey();
public abstract V getValue();
// Entries in modifiable maps must override this method
public V setValue(V value) {
throw new UnsupportedOperationException();
}
// Implements the general contract of Map.Entry.equals
@Override public boolean equals(Object o) {
if (o == this)
return true;
if (! (o instanceof Map.Entry))
return false;
Map.Entry<?,?> arg = (Map.Entry) o;
return equals(getKey(), arg.getKey()) &&
equals(getValue(), arg.getValue());
}
private static boolean equals(Object o1, Object o2) {
return o1 == null ? o2 == null : o1.equals(o2);
}
// Implements the general contract of Map.Entry.hashCode
@Override public int hashCode() {
return hashCode(getKey()) ^ hashCode(getValue());
}
private static int hashCode(Object obj) {
return obj == null ? 0 : obj.hashCode();
  }
}
4、最后要注意的是,当演变容易性比灵活性更重要时,应使用抽象类来定义类型。、

     接口一旦被公开发行,并且被广泛使用,想再更改(添加新方法等)几乎是不可能的。



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值