• 设计模式之适配器模式


      适配器模式就是把一个类的接口变换成客户端期望的接口,从而使因接口不匹配无法工作的两类可以在一起工作。

    现实场景

      笔记本电源是三向电源插头,但是遇到了电源插座却是两向的,这是就需要一个适配器排插。

    适配器模式设计的角色:

    • 源角色(Adaptee):现在需要适配的接口,如上面的两向电源插口;
    • 目标角色(Target):目标角色,也就是所期待得到的接口,如上面的笔记本的三向电源插头;
    • 适配器角色(Adapter):适配器类是本模式的核心。适配器把源接口转换成目标接口,显然,这一角色不可以是接口,而必须是具体类;如上面的排插。

    适配器模式实现方法

      类适配器模式和对象适配器模式

    类模式适配器

    /**
     * Adaptee 源角色 如例子中的双向插口*/
    public class Adaptee {
        public void charge(){
            System.out.println("插入两向插头,给你充电了......");
        }
    }
    /**
     * Target 目标角色 如例子中的三向插口*/
    public interface Target {
        void charge();
    }
    /**
     * Adapter 对象适配器 如例子中的插排*/
    public class Adapter extends Adaptee implements Target{
        @Override
        public void charge() {
            super.charge();
        }
    }
    /**
     * Client 客户端,如同例子中的 笔记本*/
    public class Client {
    
        /**
         * 充电
         */
        public void Test(Target target){
            target.charge();
        }
        public static void main(String[] args) {
            Client client = new Client();
            Target target = new Adapter();
            client.Test(target);
        }
    }

    对象适配器模式

    /**
     * Adaptee 源角色 如例子中的双向插口*/
    public class Adaptee {
        public void charge(){
            System.out.println("插入两向插头,给你充电了......");
        }
    }
    /**
     * Target 目标角色 如例子中的三向插口*/
    public interface Target {
        void charge();
    }
    /**
     * ObjectAdapter 对象适配器 如例子中的排插*/
    public class ObjectAdapter implements Target {
    
        private Adaptee adaptee;
    
        @Override
        public void charge() {
            adaptee.charge();
        }
        public ObjectAdapter(Adaptee adaptee) {
            super();
            this.adaptee = adaptee;
        }
    }
    /**
     * Client 客户端,如同例子中的 笔记本*/
    public class Client {
    
        /**
         * 充电
         */
        public void Test(Target target){
            target.charge();
        }
        
        public static void main(String[] args) {
            Client client = new Client();
            Adaptee adaptee = new Adaptee();
            Target target2 = new ObjectAdapter(adaptee);
            client.Test(target2);
        }
    }

     建议尽量使用对象适配器的实现方式,多用合成/聚合、少用继承。

  • 相关阅读:
    Silverlight 游戏开发小技巧:扇形排列元素
    Silverlight C# 游戏开发:L9 天空盒
    快乐技术开发者沙龙银光聚会第二期
    Silverlight 游戏开发小技巧:动感弹出动画
    Silverlight 游戏开发:可重用的拖拽控件
    获微软MVP
    Silverlight 游戏开发小技巧:动感小菜单1
    Protobuf语言指南
    使用xrdp或Xmanager 远程连接 CentOS6
    Linux 下使用 NMON 分析系统性能(其他如dstat、iostat)
  • 原文地址:https://www.cnblogs.com/parryyang/p/5832286.html
Copyright © 2020-2023  润新知