美文网首页
设计模式: Adapter适配器模式

设计模式: Adapter适配器模式

作者: Gascognya | 来源:发表于2020-10-10 12:52 被阅读0次

逛图书馆逛回来一本《图解设计模式》,像我这种其实并不爱看纸质书的人,也能看得进去,说明讲的还是很通俗易懂的。
这个坑中,聊一聊我对23种设计模式的个人理解。

适配器模式有两种,一是给类做代理(继承),二是给实例做代理(委托)。

继承式Adapter

继承式

继承式中,适配器本身是被适配类的子类,实现来自接口的方法,将来自继承的方法进行包装。

public class UseClass {
    void methodB() {
        System.out.println("被适配的方法methodB");
    }
}
--------------------------------
public interface Adapter {
    void methodA();
}


public class AdapterImpl extends UseClass implements Adapter{
    @Override
    public void methodA() {
        methodB();
    }
}
--------------------------------
public class Main {
    public static void main(String[] args) {
        Adapter adapter = new AdapterImpl();
        adapter.methodA();
    }
}

委托式Adapter

委托式

委托式中,不再继承于被适配的类,包装自身方法。
而是接收被适配类的实例,调用其被适配方法。

相关文章

网友评论

      本文标题:设计模式: Adapter适配器模式

      本文链接:https://www.haomeiwen.com/subject/gcgdpktx.html