赞
踩
适配器模式(Adapter Pattern)是一种结构型设计模式,用于将一个已有类的接口转换成需要的接口形式,是为了让原本接口不兼容的类可以互相作用。适配器模式通过创建一个适配器类,该适配器类实现了目标接口,并持有一个被适配类的对象。适配器类通过调用被适配类的方法来实现目标接口的方法,从而将被适配类的接口转换成目标接口。
简单里说:就是我们生活中的接口转换器,手机充电器(将 220V 转换为 5V 的电压)等等
优点:
缺点:
对象适配器
- // 原始接口
- interface Shape {
- void draw();
- }
-
- // 原始类
- class Rectangle implements Shape {
- public void draw() {
- System.out.println("Rectangle draw()");
- }
- }
-
- // 适配器类
- class ObjectAdapter implements Shape {
- private Rectangle rectangle;
-
- public ObjectAdapter(Rectangle rectangle) {
- this.rectangle = rectangle;
- }
-
- public void draw() {
- rectangle.draw();
- }
- }
-
- // 测试代码
- public class ObjectAdapterTest {
- public static void main(String[] args) {
- Rectangle rectangle = new Rectangle();
- Shape shape = new ObjectAdapter(rectangle);
- shape.draw();
- }
- }

注意就是在适配器类中,实现的类中注入未实现的接口。
类适配器
- // 原始类
- class Rectangle {
- void draw() {
- System.out.println("Rectangle draw()");
- }
- }
-
- // 目标接口
- interface Shape {
- void draw();
- }
-
- // 适配器类
- class ClassAdapter extends Rectangle implements Shape {
- public void draw() {
- super.draw();
- }
- }
-
- // 测试代码
- public class ClassAdapterTest {
- public static void main(String[] args) {
- Shape shape = new ClassAdapter();
- shape.draw();
- }
- }

其实就是一个类的继承和接口的实现,super接口的方法,然后使用时候直接调用方法即可。
看下这个博主的示例,我觉得更好的理解!!!https://blog.csdn.net/weixin_45663027/article/details/134170885
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。