zoukankan      html  css  js  c++  java
  • 设计模式-适配器模式(Adapter)

    适配器模式是构造型模式的一种,通过Adapter模式可以改变已有类的接口形式。

    角色和职责:

    1.目标(Target):

       维护对行为实现(Implementor)的引用

    2.源 -Current:

    3.适配器(Adapter)-Adapter:

    UML图:

    具体代码:

    /**
     * 当前用电
     */
    public class Current {
        public void electro(){
            System.out.println("当前用电220v");
        }
    }
    /**
     * 适配器
     */
    public class Adapter {
        private Current current;
        public Adapter(Current current){
            this.current = current;
        }
    
        /**
         * 使用适配器转成18v的电压
         */
        public void electroAdapter18(){
            this.current.electro();
            System.out.println("使用适配器,转成电压18v");
        }
    }
    public class Main {
        public static void main(String[] args) {
            Current current = new Current();//当前电压
    
            //使用适配器转成18v电压
            Adapter adapter = new Adapter(current);
            adapter.electroAdapter18();
        }
    }

    结果:

    当前用电220v
    使用适配器,转成电压18v

    优缺点:

    优:可以在不修改原有代码的基础上复用现有的类,很好的遵守“开闭原则”

    缺:针对基本代码,重定义Adaptee的行为比较困难,这就需要生成Adaptee的子类并且使得Adapter引用这个子类而不是Adaptee本身

    应用场景:

    系统需要复用现有类,而该类的接口不符合系统的需求。

    源码地址:https://github.com/qjm201000/design_pattern_adapter.git

  • 相关阅读:
    MVC3.0与C#截取字符串
    MVC3.0图片滚动和相册展示(上)
    MVC3.0视频点播及上传格式转化
    职位VS能力
    liblfds 测试
    dpdk 相关概念
    WAR文件
    在word中选择一个矩形区域
    IP地址 网段的划分
    ipconfig...ping...netstat
  • 原文地址:https://www.cnblogs.com/qjm201000/p/10072054.html
Copyright © 2011-2022 走看看