天天看點

23種設計模式之-擴充卡模式

擴充卡模式 Adapter Pattern

    • 1.類擴充卡
    • 2.對象擴充卡

擴充卡模式又叫變壓器模式,它的功能是将一個類的接口變成用戶端所期望的另一種接口,進而使原本因接口不比對而導緻無法在一起工作的兩個類能夠在一起工作。

  • 1.已存在的類,它的方法和需求不比對(方法結果相同或者相似)的情況。
  • 2.擴充卡模式不是軟體設計階段考慮的設計模式,是随着軟體的維護,由于産品的不同,不同需求造成類似功能而接口不同情況下的解決方案。

優點

  • 1.可以提高類的透明性和複用,現在的類的複用但不需要改變
  • 2.目标類和适配類解耦,提高程式的擴充性
  • 3.在很多場景下符合開閉原則

1.類擴充卡

23種設計模式之-擴充卡模式
public interface Target {

    public int request();
}
           
public class Adaptee {

    public int specificRequest()
    {
        return 220;
    }
}
           
public class Apapter extends Adaptee implements Target {

    @Override
    public int request() {
        return super.specificRequest() / 10;
    }
}
           
public class AdapterTest {

    public static void main(String[] args) {
        Apapter apapter = new Apapter();
        int  specificRequest = apapter.specificRequest();
        int request = apapter.request();

        System.out.println(specificRequest);
        System.out.println(request);
    }
}
           

2.對象擴充卡

23種設計模式之-擴充卡模式
public interface Target {

    public int request();
}
           
public class Adaptee {

    public int specificRequest()
    {
        return 220;
    }
}
           
public class Apapter implements Target {

    private Adaptee adaptee;
    public Apapter(Adaptee adaptee)
    {
        this.adaptee = adaptee;
    }

    @Override
    public int request() {
        return adaptee.specificRequest() / 10;
    }
}
           
public class AdapterTest {

    public static void main(String[] args) {
        Target target = new Apapter(new Adaptee());
        target.request();
    }
}