大话设计模式----适配器模式

一、适配器:将一个类的接口转换成客户希望的另外一个接口。Adapter模式使得原本由于接口不兼容而不能一起工作的那些类可以一起工作。

二、‘代码示例

public class Target {
    public void request(){
        System.out.println("普通请求");
    }
}

public class Adaptee {

    public void specificRequest(){
        System.out.println("特殊请求");
    }
}

@Data
public class Adapter extends Target{
    private Adaptee adaptee = new Adaptee();

    @Override
    public void request(){
        adaptee.specificRequest();
    }
}

public class Test {
    public static void main(String[] args) {
        Target target = new Adapter();
        target.request();
    }
}

三、使用场景

  1.系统的数据和行为都正确,但是接口不符时,我们就应该考虑用适配器。适配器主要应用是希望复用一些现存的类,但是接口又与复用环境要求不一致的情况。

  2.两个类所做的事情相同或相似,但是具有不同的接口,双方都不容改变时需要使用适配器。

posted @ 2020-04-08 18:05  Eden-programmer  阅读(78)  评论(0)    收藏  举报