對(duì)象的適配器模式是各種模式的起源
二:對(duì)象的適配器模式(組合的實(shí)現(xiàn))
基本思路和類的適配器模式相同,只是將Adapter類作修改,這次不繼承Source類,而是持有Source類的實(shí)例
public interface Targetable {
/* 與原類中的方法相同 */
public void method1();
/* 新類的方法 */
public void method2();
}
public class Source {
public void method1() {
System.out.println("this is original method!");
}
}
public class Wrapper implements Targetable {
private Source source;
public Wrapper(Source source){
super();
this.source = source;
}
@Override
public void method2() {
System.out.println("this is the targetable method!");
}
@Override
public void method1() {
source.method1();
}
}
public class AdapterTest {
public static void main(String[] args) {
Source source = new Source();
Targetable target = new Wrapper(source); //這里注意
target.method1();
target.method2();
}
}
一:類的適配器模式(繼承的實(shí)現(xiàn))
將Source的method1() 方法擴(kuò)展到Targetable里。
public class Source {
public void method1() {
System.out.println("this is original method!");
}
}
public interface Targetable {
/* 與原類中的方法相同 */
public void method1();
/* 新類的方法 */
public void method2();
}
public class Adapter extends Source implements Targetable {
@Override
public void method2() {
System.out.println("this is the targetable method!");
}
}
使用
public class AdapterTest {
public static void main(String[] args) {
Targetable target = new Adapter(); //這里注意
target.method1();
target.method2();
}
}
三:接口的適配器模式
起因:一個(gè)接口中有多個(gè)抽象方法,當(dāng)我們寫該接口的實(shí)現(xiàn)類時(shí),必須實(shí)現(xiàn)該接口的所有方法,這明顯有時(shí)比較浪費(fèi),因?yàn)椴⒉皇撬械姆椒ǘ际俏覀冃枰?,有時(shí)只需要某一些。接口的適配器模式應(yīng)運(yùn)而生。。。。
public interface Sourceable {
public void method1();
public void method2();
}
public abstract class Wrapper2 implements Sourceable{
public void method1(){}
public void method2(){}
}
public class SourceSub1 extends Wrapper2 {
public void method1(){
System.out.println("the sourceable interface's first Sub1!");
}
}
public class SourceSub2 extends Wrapper2 {
public void method2(){
System.out.println("the sourceable interface's second Sub2!");
}
}
public class WrapperTest {
public static void main(String[] args) {
Sourceable source1 = new SourceSub1();
Sourceable source2 = new SourceSub2();
source1.method1();
source1.method2();
source2.method1();
source2.method2();
}
}
總結(jié):
- 類的適配器模式:當(dāng)希望將一個(gè)類轉(zhuǎn)換成滿足另一個(gè)新接口的類時(shí),可以使用類的適配器模式,創(chuàng)建一個(gè)新類,繼承原有的類,實(shí)現(xiàn)新的接口即可。
- 對(duì)象的適配器模式:當(dāng)希望將一個(gè)對(duì)象轉(zhuǎn)換成滿足另一個(gè)新接口的對(duì)象時(shí),可以創(chuàng)建一個(gè)Wrapper類,持有原類的一個(gè)實(shí)例,在Wrapper類的方法中,調(diào)用實(shí)例的方法就行。
- 接口的適配器模式:當(dāng)不希望實(shí)現(xiàn)一個(gè)接口中所有的方法時(shí),可以創(chuàng)建一個(gè)抽象類Wrapper,實(shí)現(xiàn)所有方法,我們寫別的類的時(shí)候,繼承抽象類即可。