設計模式-適配器

一、適配器模式的做用:java

  •     將一個類的接口轉換成客戶但願的另一個接口。Adapter模式使得本來因爲接口不兼容而不能一塊兒工做的那些類能夠一塊兒工做。ide


二、適用性:this

  • 想使用一個已經存在的類,而它的接口不符合你的需求。spa

  • 想建立一個能夠複用的類,該類能夠與其餘不相關的類或不可預見的類(即那些接口可能不必定兼容的類)協同工做。
    code

  • (僅適用於對象A d a p t e r )想使用一些已經存在的子類,可是不可能對每個都進行子類化以匹配它們的接口。對象適配器能夠適配它的父類接口。  orm

三、例子:對象

接口1:IPeople1接口

public interface IPeople1 {
    void trot();
}

實現IPople1:People1ci

public class People1 implements IPeople1{
 
    @Override
    public void trot() {
        System.out.println("this is IPeople1's trot...");
    }
 
}

如今想經過適配器來實現--在IPeople2的walk方法中來調用IPeople1的trot; 
添加一個IPeople1的適配器:People1Adapter it

public class People1Adapter implements IPeople2 {
    private IPeople1 people1;
 
    public People1Adapter(IPeople1 people1){
        this.people1 = people1;
    }
 
    @Override
    public void walk() {
        System.out.println("this is IPeople2's walk");
        people1.trot();
    }
     
 
}

同上, 
添加一個IPeople2的適配器:People2Adapter 

public class People2Adapter implements IPeople1 {
    private IPeople2 people2;
 
    public People2Adapter(IPeople2 people2){
        this.people2 = people2;
    }
    @Override
    public void trot() {
        System.out.println("this is IPeople1's trot");
        people2.walk();
    }
 
}

最後客戶端調用: 

private static void testPeople2Adapter() {
        //Test People2Adpter
        IPeople2 people2 = new People2();
        IPeople1 people1 = new People2Adapter(people2);
        people1.trot();
    }

上面兩段分別輸入:

this is IPeople2's walk
this is IPeople1's trot...
相關文章
相關標籤/搜索