一、概述
适配器模式是一种结构型设计模式,它可以将一个类的接口转换成客户端所期望的另一个接口,使得原本由于接口不兼容而不能一起工作的类可以在一起工作。
二、代码示例(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
方法,实际上执行的是Adaptee
的specificRequest
方法。这样就实现了将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
类的方法。