对象适配器(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
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章