Prefer interfaces to abstract classes
其中一段:
Interfaces allow the construction of nonhierarchical type frameworks.
Type hierarchies are great for organizing some things, but other things don’t fall
neatly into a rigid hierarchy. For example, suppose we have an interface representing
a singer and another representing a songwriter:
public interface Singer {
AudioClip sing(Song s);
}
public interface Songwriter {
Song compose(boolean hit);
}
In real life, some singers are also songwriters. Because we used interfaces
rather than abstract classes to define these types, it is perfectly permissible for a
single class to implement both Singer and Songwriter. In fact, we can define a
third interface that extends both Singer and Songwriter and adds new methods
that are appropriate to the combination:
public interface SingerSongwriter extends Singer, Songwriter {
AudioClip strum();
void actSensitive();
}
You don’t always need this level of flexibility, but when you do, interfaces are
a lifesaver. The alternative is a bloated class hierarchy containing a separate class
for every supported combination of attributes. If there are n attributes in the type
system, there are 2^n possible combinations that you might have to support. This is
what’s known as a combinatorial explosion. Bloated class hierarchies can lead to
bloated classes containing many methods that differ only in the type of their arguments,
as there are no types in the class hierarchy to capture common behaviors .
问题:
1. 这里提到的在type system中的attributes是指什么,因为对示例接口而言,没有域,难不成是指方法?
2. 为什么会有2^n种可能组合?假如有abc三个属性,那是(),(a),(b),(c),(a,b),(a,c)(b,c),(a,b,c)=2^3
如果是这个意思,它又要如何support?
3. Bloated class hierarchies can lead to bloated classes containing many methods that differ only in the type of their arguments, why? 为什么只能在参数类型上有区别?
4. there are no types in the class hierarchy to capture common behaviors?
这句话如何解释?
thanks in advance!
my answer:
因为是替代方案,所以试着对比着来看
interface:
public interface SingerSongwriter extends Singer, Songwriter {
AudioClip strum();
void actSensitive();
}
实际上它有4个方法
bloated class hierarchy:
就可能有
class SingerSongwriter extends Singer{
AudioClip sing(Song s);
Song compose(boolean hit);
AudioClip strum();
void actSensitive();
}
or
class SingerSongwriter extends Songwriter {
AudioClip sing(Song s);
Song compose(boolean hit);
AudioClip strum();
void actSensitive();
}
但 无论哪一种,都会缺失一种类型(there are no types in the class hierarchy to capture common behaviors),以及可能连带缺失的类型,比如Song等,这样可能就会导致Bloated class hierarchies can lead to bloated classes containing many methods that differ only in the type of their arguments。
同时也满足了一个类包含所有可能属性组合(The alternative is a bloated class hierarchy containing a separate class for every supported combination of attributes.),我觉得这里可以把attributes理解为方法之类的,方法也属于对象属性之一。这里恰好是2^2=4,有点全组合的味道, 但是不知道strum()和actSensitive怎么来的,权且把strum看成是sing和compose组合的产物,actSensitive代 表全组合中的空,这样就能解释2^n,总的来说还有些牵强的地方,但不知道他说的是否100%精准。