JAVA 适配器模式讲解和代码示例

简介: JAVA 适配器模式讲解和代码示例

使用示例:适配器模式在 Java 代码中很常见。 基于一些遗留代码的系统常常会使用该模式。 在这种情况下, 适配器让遗留代码与现代的类得以相互合作。

Java 核心程序库中有一些标准的适配器:

  • java.util.Arrays#asList()
  • java.util.Collections#list()
  • java.util.Collections#enumeration()
  • java.io.InputStreamReader(InputStream) (返回 Reader对象)
  • java.io.OutputStreamWriter(OutputStream) (返回 Writer对象)
  • javax.xml.bind.annotation.adapters.XmlAdapter#marshal() 和 #unmarshal()

识别方法:适配器可以通过以不同抽象或接口类型实例为参数的构造函数来识别。 当适配器的任何方法被调用时, 它会将参数转换为合适的格式, 然后将调用定向到其封装对象中的一个或多个方法。

01让方钉适配圆孔

这个简单的例子展示了适配器如何让不兼容的对象相互合作。


02round

round/RoundHole.java: 圆孔

package refactoring_guru.adapter.example.round;/**
* RoundHoles are compatible with RoundPegs.
*/public class RoundHole {    private double radius;    public RoundHole(double radius) {        this.radius = radius;
    }    public double getRadius() {        return radius;
    }    public boolean fits(RoundPeg peg) {        boolean result;        result = (this.getRadius() >= peg.getRadius());        return result;
    }
}

round/RoundPeg.java: 圆钉

package refactoring_guru.adapter.example.round;/**
* RoundPegs are compatible with RoundHoles.
*/public class RoundPeg {    private double radius;    public RoundPeg() {}    public RoundPeg(double radius) {        this.radius = radius;
    }    public double getRadius() {        return radius;
    }
}

03square

square/SquarePeg.java: 方钉

package refactoring_guru.adapter.example.square;/**
* SquarePegs are not compatible with RoundHoles (they were implemented by
* previous development team). But we have to integrate them into our program.
*/public class SquarePeg {    private double width;    public SquarePeg(double width) {        this.width = width;
    }    public double getWidth() {        return width;
    }    public double getSquare() {        double result;        result = Math.pow(this.width, 2);        return result;
    }
}

04adapters

adapters/SquarePegAdapter.java: 方钉到圆孔的适配器

package refactoring_guru.adapter.example.adapters;import refactoring_guru.adapter.example.round.RoundPeg;import refactoring_guru.adapter.example.square.SquarePeg;/**
* Adapter allows fitting square pegs into round holes.
*/public class SquarePegAdapter extends RoundPeg {    private SquarePeg peg;    public SquarePegAdapter(SquarePeg peg) {        this.peg = peg;
    }    @Override
    public double getRadius() {        double result;        // Calculate a minimum circle radius, which can fit this peg.
        result = (Math.sqrt(Math.pow((peg.getWidth() / 2), 2) * 2));        return result;
    }
}

Demo.java: 客户端代码

package refactoring_guru.adapter.example;import refactoring_guru.adapter.example.adapters.SquarePegAdapter;import refactoring_guru.adapter.example.round.RoundHole;import refactoring_guru.adapter.example.round.RoundPeg;import refactoring_guru.adapter.example.square.SquarePeg;/**
* Somewhere in client code...
*/public class Demo {    public static void main(String[] args) {        // Round fits round, no surprise.
        RoundHole hole = new RoundHole(5);        RoundPeg rpeg = new RoundPeg(5);        if (hole.fits(rpeg)) {            System.out.println("Round peg r5 fits round hole r5.");
        }        SquarePeg smallSqPeg = new SquarePeg(2);        SquarePeg largeSqPeg = new SquarePeg(20);        // hole.fits(smallSqPeg); // Won't compile.
        // Adapter solves the problem.
        SquarePegAdapter smallSqPegAdapter = new SquarePegAdapter(smallSqPeg);        SquarePegAdapter largeSqPegAdapter = new SquarePegAdapter(largeSqPeg);        if (hole.fits(smallSqPegAdapter)) {            System.out.println("Square peg w2 fits round hole r5.");
        }        if (!hole.fits(largeSqPegAdapter)) {            System.out.println("Square peg w20 does not fit into round hole r5.");
        }
    }
}

OutputDemo.txt: 执行结果

Round peg r5 fits round hole r5.
Square peg w2 fits round hole r5.
Square peg w20 does not fit into round hole r5.


以上是23种设计模式漫画版系列—适配器模式,全部内容了。

相关文章
|
Java 开发工具
【Azure Storage Account】Java Code访问Storage Account File Share的上传和下载代码示例
本文介绍如何使用Java通过azure-storage-file-share SDK实现Azure文件共享的上传下载。包含依赖引入、客户端创建及完整示例代码,助你快速集成Azure File Share功能。
869 6
|
Java 数据处理 API
为什么你的Java代码应该多用Stream?从循环到声明式的思维转变
为什么你的Java代码应该多用Stream?从循环到声明式的思维转变
518 115
|
安全 Java 编译器
为什么你的Java代码需要泛型?类型安全的艺术
为什么你的Java代码需要泛型?类型安全的艺术
415 98
|
Java 编译器 API
java最新版和java8的区别,用代码展示
java最新版和java8的区别,用代码展示
830 43
|
安全 Java 容器
告别空指针噩梦:Optional让Java代码更优雅
告别空指针噩梦:Optional让Java代码更优雅
630 94
|
安全 Java 容器
告别繁琐判空:Optional让你的Java代码更优雅
告别繁琐判空:Optional让你的Java代码更优雅
|
IDE Java 关系型数据库
Java 初学者学习路线(含代码示例)
本教程为Java初学者设计,涵盖基础语法、面向对象、集合、异常处理、文件操作、多线程、JDBC、Servlet及MyBatis等内容,每阶段配核心代码示例,强调动手实践,助你循序渐进掌握Java编程。
1550 3
|
安全 Java 应用服务中间件
Spring Boot + Java 21:内存减少 60%,启动速度提高 30% — 零代码
通过调整三个JVM和Spring Boot配置开关,无需重写代码即可显著优化Java应用性能:内存减少60%,启动速度提升30%。适用于所有在JVM上运行API的生产团队,低成本实现高效能。
1505 3
|
JSON 网络协议 安全
【Java】(10)进程与线程的关系、Tread类;讲解基本线程安全、网络编程内容;JSON序列化与反序列化
几乎所有的操作系统都支持进程的概念,进程是处于运行过程中的程序,并且具有一定的独立功能,进程是系统进行资源分配和调度的一个独立单位一般而言,进程包含如下三个特征。独立性动态性并发性。
770 1