文章摘要: 适配器模式使用总结。
简介
简要说明
- 适配器模式(Adapter Pattern)是一种结构型设计模式。
- 当系统的客户端需要使用一些现有的类,但这些类的接口(即它们的方法和属性)不符合客户端的要求时,可以通过适配器来转换这些类的接口,使其与客户端期望的接口相匹配。
主要功能
- 允许接口不兼容的类一起工作。
- 通过使用适配器,客户端可以统一调用接口,而不必关心具体的实现类。
- 提高了类的复用性,减少了代码的重复编写。
注意事项
- 适配器模式可能会增加系统的复杂性,因为它引入了额外的类和层次结构。
- 应该在确实需要时才使用适配器模式,避免过度设计。
- 适配器模式可能会使得代码难以跟踪,特别是当适配器嵌套使用时。
适用场景
- 当你希望使用一个已经存在的类,但其接口不符合你的需求时。
- 当你想要创建一个可重用的类,该类可以与其他不相关的类或不可预见的类(即那些接口可能不一定兼容的类)协同工作。
- 当你需要在运行时选择不同的实现类时。
Java 8
案例
// 已存在的类,其接口不符合客户端的需求
class LegacyRectangle {
public void draw(int x1, int y1, int x2, int y2) {
System.out.println("Drawing rectangle from (" + x1 + ", " + y1 + ") to (" + x2 + ", " + y2 + ")");
}
}
// 客户端期望的接口
interface Shape {
void draw();
}
// 适配器类,将LegacyRectangle适配为Shape接口
class RectangleAdapter implements Shape {
private LegacyRectangle adaptee;
public RectangleAdapter(LegacyRectangle adaptee) {
this.adaptee = adaptee;
}
@Override
public void draw() {
// 假设我们希望画一个从(0,0)到(10,10)的矩形
adaptee.draw(0, 0, 10, 10);
}
}
// 客户端代码
public class AdapterPatternDemo {
public static void main(String[] args) {
LegacyRectangle legacyRectangle = new LegacyRectangle();
Shape rectangleAdapter = new RectangleAdapter(legacyRectangle);
// 客户端代码现在可以使用Shape接口来绘制矩形
rectangleAdapter.draw();
}
}
注释
- 在这个例子中,
LegacyRectangle是一个已有的类,它的draw方法接受四个参数。客户端期望使用一个Shape接口,该接口只有一个draw方法。 RectangleAdapter类实现了Shape接口,并将LegacyRectangle的draw方法适配为客户端期望的形式。- 这样,客户端就可以通过
Shape接口来操作LegacyRectangle类,而无需直接与其不兼容的接口交互。