首页 > 其他 > 详细

[设计模式]适配器模式

时间:2020-06-13 16:27:55      阅读:61      评论:0      收藏:0      [点我收藏+]

[设计模式]适配器模式

Adapter模式使得原本由于接口不兼容而不能一起工作的那些类可以一起工作。

  • 类适配器

    //接口转换器的抽象实现
    public interface NetToUSB {
        public void handleRequest();
    }
    
    //网线类
    public class NetWire {
    
        public void request(){
            System.out.println("连接网线上网!");
        }
    }
    
    //适配器类
    public class Adapter extends NetWire implements NetToUSB{
        @Override
        public void handleRequest() {
            super.request();
        }
    }
    
    //电脑类和测试方法
    public class Computer {
    
        public  void net(NetToUSB adapter){
            //上网
            adapter.handleRequest();
        }
    
        public static void main(String[] args) {
    
            Computer computer = new Computer();
            NetWire netWire = new NetWire();
            Adapter adapter = new Adapter();
    
            computer.net(adapter);
        }
    
    }
    

    缺点:

    • 对于Java、C#等不支持多重类继承的语言,一次最多只能适配一个适配者类。
    • 在Java、C#等语言中,类适配器模式中的目标抽象类只能为接口,不能为类,其使用有一定的局限性。
  • 对象适配器

    //接口转换器的抽象实现
    public interface NetToUSB {
        public void handleRequest();
    }
    
    //网线类
    public class NetWire {
    
        public void request(){
            System.out.println("连接网线上网!");
        }
    }
    
    //适配器类
    public class Adapter  implements NetToUSB{
    
        private NetWire netWire;
    
        public Adapter(NetWire netWire) {
            this.netWire = netWire;
        }
    
        @Override
        public void handleRequest() {
            netWire.request();
        }
    }
    
    //电脑类和测试方法
    public class Computer {
    
        public  void net(NetToUSB adapter){
            //上网
            adapter.handleRequest();
        }
    
        public static void main(String[] args) {
    
            Computer computer = new Computer();
            NetWire netWire = new NetWire();
            Adapter adapter = new Adapter(netWire);
    
            computer.net(adapter);
        }
    
    }
    

    优点:

    • 一个对象适配器可以把多个不同的适配者适配到同一个目标。
    • 可以适配一个适配者的子类。

[设计模式]适配器模式

原文:https://www.cnblogs.com/baihan/p/13113681.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!