Java学习笔记(9)-23种设计模式之适配器模式

2020-02-24  本文已影响0人  非典型程序猿

这篇文章开始总结结构型模式的第二种模式,适配器模式,适配器这个概念大家应该听到比较多,在使用各种ListView,RecycleView时适配器都是必要的,我们今天开始总结适配器模式的基本原理。

定义

适配器的核心思想就是将一个类中的某个接口转化为另一个新的类的访问接口,其可以实现新的功能也同时可以兼容老的接口里的业务逻辑。适配器模式分为类结构型模式和对象型结构模式,我会把两者的示例代码都举例说明。

结构

类结构型模式代码示例

/**
 * 类适配器模式
 */
public class MyTest{
    public static void main(String[] args) throws CloneNotSupportedException {
        System.out.println("开始适配器模式代码测试...");
        Adapter adapter = new Adapter();
        adapter.targetMethod();
    }
    /**
     * 需要适配的目标接口
     */
    interface Target{
        void targetMethod();
    }
    /**
     * 需要被适配的类
     */
    static class Adaptee{
        //需要被适配的对外的接口
        public static void method(){
            System.out.println("被适配的老业务已被调用...");
        }
    }
    /**
     * 适配的类,作为新的访问入口
     */
    static class Adapter extends Adaptee implements Target{
        /**
         * 新的访问入口,兼容老的内容
         */
        @Override
        public void targetMethod() {
            method();
        }
    }
}

类结构型模式写时只需两步

对象结构型模式

/**
 * 对象适配器模式
 */
public class MyTest{
    public static void main(String[] args) throws CloneNotSupportedException {
        System.out.println("开始对象适配器模式代码测试...");
        Adaptee adaptee = new Adaptee();
        Adapter adapter = new Adapter(adaptee);
        adapter.targetMethod();
    }
    /**
     * 需要适配的目标接口
     */
    interface Target{
        void targetMethod();
    }
    /**
     * 需要被适配的类
     */
    static class Adaptee{
        //需要被适配的对外的接口
        public static void method(){
            System.out.println("被适配的老业务已被调用...");
        }
    }
    /**
     * 适配的类,作为新的访问入口
     */
    static class Adapter implements Target{
        private Adaptee adaptee ;
        /**
         * 新的访问入口,兼容老的内容
         */
        public Adapter(Adaptee adaptee){
            this.adaptee = adaptee;
        }
        @Override
        public void targetMethod() {
            if(adaptee == null){
                System.out.println("适配器参数错误...");
                return;
            }
            adaptee.method();
        }
    }
}

对象型结构模式书写时需要3步

两者的对比

上一篇 下一篇

猜你喜欢

热点阅读