對象適配器(object adapter)

把一個類的接口變成客戶端所期待的另一種接口,從而使原本因接口不匹配而無法在一起工作的兩個類能夠在一起工作

 

/**
 * 目標角色
 */
public interface Target {
    public void operation1();
    public void operation2();
}

 

/**
 * 原角色
 */
public class Adaptee {

    public void operation1(){
        System.out.println("原角色的方法 operation1");
    }
}

 

/**
 * 適配器
 */
public class Adapter implements Target {

    private Adaptee adaptee;

    public Adapter(Adaptee adaptee) {
        this.adaptee = adaptee;
    }

    public void operation1() {
        adaptee.operation1();
    }

    public void operation2() {
        System.out.println("operation2");
    }
}

 

/**
 * 客戶端
 */
public class Client {

    public static void main(String[] args) {
        Adaptee adaptee = new Adaptee();
        Adapter adapter = new Adapter(adaptee);
        Client client = new Client();
        client.use(adapter);
    }
    
    public void use(Target target){
        target.operation1();
    }
}

  

發佈了45 篇原創文章 · 獲贊 0 · 訪問量 1449
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章