適配器模式(Adapter)

適配器模式git

一.適配器模式

1.1 定義

  • 將一個接口轉換成客戶但願的另外一個接口.

1.2 角色

  1. 目標接口對象(Target):客戶但願的另外一個接口或具體類.
  2. 須要適配的類(Adaptee):現有的,不符合客戶需求的接口或具體類.
  3. 適配器對象(Adapter):包裝適配的對象,轉換接口.

1.3 實現方式

  1. 類適配器(繼承).
  2. 對象適配器(聚合).

二. 具體實現

2.1 建立目標接口及實現類

public interface ITarget {
        void show();
    }
    public class Target implements ITarget{
        public Target(){
            System.out.println("create target...");
        }
        @Override
        public void show() {
            System.out.println(this.getClass().getSimpleName());
        }
    }

2.2 建立須要適配的接口及實現類

public interface IAdaptee {
    }
    public class Adaptee implements IAdaptee{
    }

2.3 類適配器

public class Adapter1 implements IAdaptee{
        ITarget target;
        public ITarget convert(IAdaptee adaptee){
            if(adaptee != null){
                target = new Target();
            }
            return target;
        }
    }

2.4 對象適配器

public class Adapter2 implements ITarget,IAdaptee{
        @Override
        public void show() {
            System.out.println(this.getClass().getSimpleName());
        }
    }

2.5 調用

public static void main(String[] args) {
        Adapter1 adapter1 = new Adapter1();
        ITarget target = adapter1.convert(new Adaptee());
        target.show();

        Adapter2 adapter2 = new Adapter2();
        adapter2.show();
    }

2.6 輸出

create target...
    Target
    Adapter2

三. 優缺點

3.1 優勢

  • 靈活性好,提升了類的複用度.

3.2 缺點

  • 過多使用會使系統雜亂.

四. 源碼

https://github.com/Seasons20/DisignPattern.git

ENDgithub

相關文章
相關標籤/搜索