zoukankan      html  css  js  c++  java
  • 23种设计模式——适配器模式

    23种设计模式——适配器模式

    结构型模式

    • 作用:从程序的结构上实现松耦合,从而可以扩大整体的类结构,用来解决更大的问题

    适配器

    • 将一个类的接口转换成客户希望的另一个接口,Adapter模式使得原本由于接口不兼容而不能一起工作的那些类可以在一起工作。

    角色分析

    • 目标接口:客户所期待的接口,目标可以是具体的或者抽象的类,也可以是接口;

    • 需要适配的类:需要适配的类或者适配者类

    • 适配器:通过包装一个需要适配的对象,把原来接口转换成目标对象

    package com.mjh.adapter;
    //要被适配的类:网线
    public class Adaptee {
        public void request(){
            System.out.println("连接上网线上网了");
        }
    }
    
    package com.mjh.adapter;
    
    //接口转换器的抽象实现
    public interface NetToUSB {
        //处理请求
        public void handerRequest();
    }
    

    1.继承的方式(类适配器 单继承)

    package com.mjh.adapter;
    
    //适配器:一端连接电脑,另一端连接网线
    public class Adapter extends Adaptee implements NetToUSB{
    
        @Override
        public void handerRequest() {
            super.request();
        }
    }
    
    //客户端:电脑,想上网
    public class Computer {
    
        public void net(NetToUSB adapter){
            //上网的具体实现,找一个转接口
          adapter.handerRequest();
        }
        
         public static void main(String[] args) {
            //电脑,网线,适配器
            Computer computer = new Computer();
            Adapter adapter = new Adapter();
            Adaptee adaptee = new Adaptee();
    
            computer.net(adapter);
        }
    }
    

    2.集合的方式(对象适配器 常用)

    package com.mjh.adapter;
    //适配器:一端连接电脑,另一端连接网线
    //2.集合的方式(对象适配器  常用)
    public class Adapter2  implements NetToUSB {
           private Adaptee adaptee;
    
        public Adapter2(Adaptee adaptee) {
            this.adaptee = adaptee;
        }
    
        @Override
            public void handerRequest() {
               adaptee.request();
            }
    
    }
    
    public static void main(String[] args) {
        //电脑,网线,适配器
        Computer computer = new Computer();
        Adaptee adaptee = new Adaptee();
        Adapter2 adapter = new Adapter2(adaptee);
    
        computer.net(adapter);
    }
    

    对象适配器的优点

    • 一个对象适配器可以把多个不同的适配者适配到同一个目标
    • 可以适配一个适配者的子类,由于适配器和是配置之间是关联关系,根据“里氏替换原则”,适配者的子类也可通过该适配器进行适配。

    类适配器的缺点

    • 对于java,c#等不支持多重继承类的语言,一次最多只能适配一个适配者类,不能同时适配多个适配者
    • 在java,c#等语言中,类适配器模式中的目标抽象类只能为接口,不能为类,其使用有一定局限性。
  • 相关阅读:
    【alpha】Scrum站立会议第2次....10.17
    【alpha】Scrum站立会议第1次····10.16
    【week4】技术随笔psp
    【week4】课堂Scrum站立会议
    【week3】psp (技术随笔)
    【week3】四则运算 单元测试
    【week3】词频统计 单元测试
    Oracle Split字符串

    指针函数与指针数组
  • 原文地址:https://www.cnblogs.com/mjjh/p/13327033.html
Copyright © 2011-2022 走看看