1、當(dāng)一個接口中有很多抽象方法,并且其有很多實(shí)現(xiàn)類,但是有些類不需要接口中某些方法。這樣就會造成大量冗余的實(shí)現(xiàn)接口的方法。
比如:
改進(jìn)前:
接口
public interface TestInterface{
void method1();
int method2();
boolean method3();
}
實(shí)現(xiàn)類1:
public class TestClass1 implements TestInterface{
public void method1(){
}
public int method2(){
return 1;
}
public int method3(){
return true;
}
}
實(shí)現(xiàn)類2:
public class TestClass2 implements TestInterface{
public void method1(){
}
public int method2(){
return 1;
}
public int method3(){
return true;
}
}
可以發(fā)現(xiàn):兩個實(shí)現(xiàn)類必須都要實(shí)現(xiàn)接口中的所有方法,如果實(shí)現(xiàn)類2只需要擁有method1方法的功能,這樣就會造成代碼冗余。如果接口的方法很多,實(shí)現(xiàn)類的也很多,那么就會造成大量不必要的方法重寫。
改進(jìn)后:
增加一個抽象類:
public abstract class TestAbstract implements TestInterface{
//找出接口中必要的方法,也就是子類必須實(shí)現(xiàn)的方法,定義成抽象方法,交由子類實(shí)現(xiàn)
public abstract void method1();
public abstract int method2();
//一些獨(dú)特的方法可以在抽象類中默認(rèn)實(shí)現(xiàn)
public boolean method3(){
return true;
}
}
實(shí)現(xiàn)類1:
public class TestClass1 extends TestAbstract {
public void method1(){
}
public int method2(){
return 1;
}
//重寫抽象類中的方法
public int method3(){
return false;
}
}
實(shí)現(xiàn)類2:
public class TestClass2 extends TestAbstract {
public void method1(){
}
public int method2(){
return 1;
}
}
可以發(fā)現(xiàn):實(shí)現(xiàn)類2中只需要實(shí)現(xiàn)接口中的必要的方法就ok。
通過接口和抽象類的結(jié)合,避免了在實(shí)現(xiàn)接口的子類中出現(xiàn)大量的“無意義”實(shí)現(xiàn),這個“無意義”實(shí)現(xiàn),被緩沖到了抽象類中,完美展現(xiàn)了代碼復(fù)用(可以把抽象類理解成接口和實(shí)現(xiàn)類之間的緩沖)。
這樣做的好處不僅僅是這一點(diǎn),細(xì)細(xì)品味,假如我們向接口中增加了一個方法。。。
向接口中新增的方法,可以在實(shí)現(xiàn)接口的抽象類中緩沖一下,提供一個默認(rèn)的實(shí)現(xiàn),這樣一來,就不必強(qiáng)制所有的子類(通過繼承抽象類間接實(shí)現(xiàn)接口的類)都進(jìn)行修改,可以形象的理解為“沒有驚動子類”。而需要使用這個方法的子類,直接重寫即可。
接口和抽象類結(jié)合,產(chǎn)生了優(yōu)雅的缺省適配模式。