Java设计模式(六)适配器模式

一、概述

适配器模式是一种结构型设计模式,它可以将一个类的接口转换成客户端所期望的另一个接口,使得原本由于接口不兼容而不能一起工作的类可以在一起工作。

二、代码示例(1)

//1.目标接口
public interface Target {
    void request();
}

//2.源接口
public interface Adaptee {
    void specificRequest();
}

//3.源接口的适配器
public class AdapteeAdapter implements Target {
    private Adaptee adaptee;

    public AdapteeAdapter(Adaptee adaptee) {
        this.adaptee = adaptee;
    }

    @Override
    public void request() {
        adaptee.specificRequest();
    }
}

//4.源接口的实现类
public class ConcreteAdaptee implements Adaptee{
    @Override
    public void specificRequest() {
        System.out.println("Adaptee: specificRequest");
    }
}

//5.测试类
public class Test {
    public static void main(String[] args) {
        Adaptee adaptee = new ConcreteAdaptee();
        Target target = new AdapteeAdapter(adaptee);
        target.request(); // 调用适配器的request方法,实际上执行的是Adaptee的specificRequest方法
    }
}

上述代码中,Target是目标接口,Adaptee是源接口,AdapteeAdapter是源接口的适配器,实现了目标接口,它将目标接口的请求转换成源接口的特定请求。ConcreteAdaptee是源接口的实现类,它实现了源接口的specificRequest方法。

在测试类中,首先创建一个ConcreteAdaptee对象作为源接口的实现类,然后将其传入AdapteeAdapter的构造函数中,创建一个AdapteeAdapter对象作为目标接口的实现类,然后调用其request方法,实际上执行的是AdapteespecificRequest方法。这样就实现了将Adaptee适配成了Target接口。

三、代码示例(2)

在适配器模式中,适配器是扮演着将一个类的接口转换为客户端希望的另一个接口的角色。适配器可以帮助原本不兼容的类能够协同工作。

下面是一个简单的适配器模式的代码示例,假设我们有一个已经存在的类 Square ,但是我们需要将其适配为符合 Shape 接口的类。

//1.目标类,代表一个形状
public interface Shape {
    void draw(int x, int y, int z, int j);
}

//2.一个实际的形状,正方形
public class Square {
    public void drawSquare(int x1, int y1, int x2, int y2) {
        System.out.println("正方形坐标是: "
                + "(" + x1 + ", " + y1 + "), (" + x2 + ", " + y2 + ")");
    }
}

//3.正方形转形状的适配器
public class SquareAdapter implements Shape {
    private Square square;

    public SquareAdapter(Square square) {
        this.square = square;
    }

    @Override
    public void draw(int x, int y, int z, int j) {
        // 适配器将参数进行转换,并调用原有的 Square 类的方法
        int x1 = x;
        int y1 = y;
        int x2 = x + z;
        int y2 = y + j;
        square.drawSquare(x1, y1, x2, y2);
    }
}

//4.测试类
public class Test {
    public static void main(String[] args) {
        // 原有的 Square 类并没有实现 Shape 接口
        Square square = new Square();

        // 使用适配器将 Square 类适配为 Shape 接口
        Shape shape = new SquareAdapter(square);

        // 客户端代码可以使用 Shape 接口调用 Square 类的方法
        shape.draw(10, 20, 30, 40);
    }
}

在上述示例中,我们创建了一个适配器类 SquareAdapter ,将 Square 类适配为符合 Shape 接口的类。通过适配器类的转换,测试类代码可以使用 Shape 接口调用 Square 类的方法。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Dantesding

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值