栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

设计模式——适配器模式

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

设计模式——适配器模式

适配器模式 1. 实现
  1. 找到两个维度(本次用类型和品牌举例)
  2. 对两个维度进行抽象
    public interface Brand {
       void info();
    }
    
    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    public abstract class Computer {
        protected Brand brand;
        public void info() {
            brand.info();
        }
    }
    
  3. 实现抽象类和接口
    public class Apple implements Brand {
        public void info() {
            System.out.print("This is Apple ");
        }
    }
    
    public class Lenovo implements Brand {
        public void info() {
            System.out.print("This is Lenovo ");
        }
    }
    
    public class Desktop extends Computer {
        public Desktop(Brand brand) {
            super(brand);
        }
    
        public Desktop() {
        }
    
        @Override
        public void info() {
            super.info();
            System.out.println("This is Desktop");
        }
    }
    public class Laptop extends Computer {
    
        public Laptop() {
        }
    
        public Laptop(Brand brand) {
            super(brand);
        }
    
        @Override
        public void info() {
            super.info();
            System.out.println("This is Laptop");
        }
    }
    
  4. 测试
    public class Main {
        public static void main(String[] args) {
            Computer appleLaptop = new Laptop(new Apple());
            appleLaptop.info();
    
            Computer lenovoDesktop = new Desktop(new Lenovo());
            lenovoDesktop.info();
        }
    }
    
2. 总结
  • 优点:提高了系统的可扩展性 在两个变化维度中任意扩展不会影响到整个程序 符合开闭原则

  • 缺点:适用范围具有一定局限性

  • 如果系统中存在两个变化维度,且这两个维度都要扩展,适用桥接模式

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/285425.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号