适配器模式

128 阅读1分钟
/**
 * 适配器模式
 * 个人理解:1.为了解决两个接口不兼容问题,在不改动两个接口的前提下,使用适配器模式
 *  2.分为类模式和对象模式,基于java单继承和合成复用原则,尽量使用对象模式
 * 组件:目标接口(Target)、调用类(Source)、适配器类(Adaptor)、客户类(Client)
 */
public class AdaptorDesignPattern {

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

}

interface Target {
    void request();
}

class Source {

    public void doSomething() {
        System.out.println("do something...");
    }
}

class Adaptor implements Target {
    private Source source;
    public Adaptor() {
        source = new Source();
    }

    @Override
    public void request() {
        source.doSomething();
    }
}