Java 提供兩種為同一份抽象給出多種實作的機制:介面(interface)與抽象類別(abstract class)。除了「能否提供基本實作」這個明顯差異之外,還有一條更關鍵的分野:實作介面的類可以位於類別層級的任何位置,而繼承抽象類別的子類卻被層級結構牢牢綁住。
Existing classes can be easily retrofitted to implement a new interface.
要讓一個既有類別實作新介面,只要加上 implements 與方法實作即可;反過來說,去繼承一個抽象類別可能弄壞原本的層級。當分屬兩個不同層級的類別都需要同一份抽象行為時,你被迫重排整條繼承鏈。
Interfaces are ideal for defining mixins.
「mixin」這個詞不好翻,硬譯成「混合類型」也顯得僵硬。這條其實與上一點在說同一件事。書中以 Comparable 為例:實作它就等於宣告自己的實例之間可以互相比較。抽象類別沒辦法這樣隨意嵌進既有類別,因此要為類別補上一項行為時,介面才是合適的載體。
Interfaces allow the construction of nonhierarchical type frameworks.
層級結構並非一無是處,但值得先問一句:真的需要嚴格的層級嗎?歌手與作曲家之間有沒有層級關係?顯然沒有。
public interface Singer {
AudioClip sing(Song s);
}
public interface Songwriter {
Song compose(boolean hit);
}
如果碰上創作型歌手,他得同時具備兩種能力。所幸兩者都是介面:
public interface SingerSongwriter extends Singer, Songwriter {
AudioClip strum();
void actSensitive();
}
改用抽象類別來解同一個問題,你要嘛把一個類別的物件塞進另一個類別當欄位,要嘛硬把它們排進層級裡。一旦組合的種類變多,結構就迅速膨脹,也就是所謂的 combinatorial explosion。
介面最常被詬病的「無法提供任何實作」,並不足以讓抽象類別取而代之。更好的策略是兩者搭配:為介面提供一個抽象骨架實作(skeletal implementation)。Apache Shiro 的 DefaultSecurityManager 層級就是這種思路。
這類骨架類別有固定的命名慣例,例如 AbstractSet 對 Set、AbstractCollection 對 Collection。書中的例子用靜態工廠方法回傳骨架類別的匿名子類,把整數陣列包成 List:
public class IntArrays {
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];
}
@Override
public Integer set(int i, Integer val) {
int oldVal = a[i];
a[i] = val;
return oldVal;
}
public int size() {
return a.length;
}
};
}
}
Shiro 的 org.apache.shiro.realm.Realm 介面文件也寫得很坦白:
Most users will not implement the Realm interface directly, but will extend one of the subclasses, AuthenticatingRealm or AuthorizingRealm, greatly reducing the effort required to implement a Realm from scratch.
也就是說,直接實作介面往往枯燥又冗長,官方更希望你繼承 CachingRealm、AuthenticatingRealm、AuthorizingRealm 之類的子類;也有 ModularRealmAuthenticator 這種簡單實作可參考。
骨架類別的經典範例莫過於 AbstractMapEntry:
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();
}
}
寫骨架類別比寫普通實作類別多幾重限制:你得先判斷介面裡哪些才是最基礎的行為並留給子類,骨架只負責其餘方法;同時要留意繼承可能打破封裝,並為「為繼承而設計」補上文件,標明哪些方法是 self-use、是否實作了 Serializable 或 Cloneable 等。
抽象類別還有一項優勢——它的變化比介面容易。後續版本要替抽象類別加方法,成本遠低於替介面加方法;而在不破壞既有實作的前提下,往公開介面裡新增方法幾乎不可能,因為沿著繼承鏈往下追,總會有具體實作類別存在。所以設計介面是技術活,一旦定案就別想再改。
抽象類別與介面之間的取捨,某種角度上就是「易擴充性」與「靈活性」之間的取捨。