1. 程式人生 > 實用技巧 >java基礎---設計模式(2)

java基礎---設計模式(2)

結構型模式

一、介面卡模式

  介面卡模式將某個類的介面轉換成客戶端期望的另一個介面表示,目的是消除由於介面不匹配所造成的類的相容性問題 ,包括類的介面卡模式、物件的介面卡模式、介面
的介面卡模式

  • 類的介面卡模式

 

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!"); } } //Adapter類繼承Source類,實現Targetable介面,下面是測試類: public class AdapterTest { public static
void main(String[] args) { Targetable target = new Adapter(); target.method1(); target.method2(); } } //this is original method! //this is the targetable method!
  • 物件的介面卡模式

  將Adapter類作修改,這次不繼承Source類,而是持有Source類的例項,以達到解決相容性的問題

//修改adapter
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(); //直接呼叫了物件的method1 進行重寫 } } //測試類: public class AdapterTest { public static void main(String[] args) { Source source = new Source(); Targetable target = new Wrapper(source); target.method1(); target.method2(); } }
  • 介面的介面卡模式

 藉助於一個抽象類,該抽象類實現了該介面所有的方法,而我們不和原始的介面打交道,只和該抽象類取得聯絡,所以我們寫一個類,繼承該抽象類,重寫我們需要的方法

//原介面
public interface Sourceable {
    
    public void method1();
    public void method2();
}

//抽象類Wrapper2實現了介面的方法,不重寫
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();
    }
}

//the sourceable interface's first Sub1!
//the sourceable interface's second Sub2!