当你有两个不兼容的接口,但需要他们能够一起工作时,适配器模式可以解决这个问题,例如,你可能有一个已存在的类库或组件,但其接口与你的代码不匹配,你希望能够无缝衔接的将他们集成在一起。
适配器模式的应用可以使得现有的代码和新代码能够无缝协同工作,从而提高了代码的可用性。它允许你将不同系统,库或者组件整合在一起,而不许对现有的代码进行大量修改,然而,适配器模式也可能引入一些复杂性,因为你需要维护适配器类和处理不同接口之间的映射关系。总的来说适配器模式是一种很有用的模式,特别适合在集成不同组件或者类时,解决接口不匹配的问题,从而保持代码的灵活性和可维护性。
已存在的LegacyRectangle类 class LegacyRectangle { public void display(int x1, int y1, int x2, int y2) { System.out.println("LegacyRectangle: Point1(" + x1 + ", " + y1 + "), Point2(" + x2 + ", " + y2 + ")"); } } // 统一的Shape接口 interface Shape { void draw(int x, int y, int width, int height); } // 适配器类,将LegacyRectangle适配到Shape接口上 class RectangleAdapter implements Shape { private LegacyRectangle legacyRectangle; public RectangleAdapter(LegacyRectangle legacyRectangle) { this.legacyRectangle = legacyRectangle; } @Override public void draw(int x, int y, int width, int height) { int x1 = x; int y1 = y; int x2 = x + width; int y2 = y + height; legacyRectangle.display(x1, y1, x2, y2); } } // 在这个示例中,LegacyRectangle是已经存在的类,而RectangleAdapter是适配器类,用于将LegacyRectangle适配到Shape接口上。 // 客户端代码通过使用适配器来画一个矩形,实际上是在调用了LegacyRectangle的display方法,但是通过适配器,它符合了Shape接口的标准。 public class AdapterPatternExample { public static void main(String[] args) { LegacyRectangle legacyRectangle = new LegacyRectangle(); Shape shapeAdapter = new RectangleAdapter(legacyRectangle); shapeAdapter.draw(10, 20, 50, 30); }
AI 代码解读
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.
38.
39.
简单的理解:手机充电器也叫电源适配器,它是将220V的交流电转换成5V的直流电,代码中的适配器模式也是同样的作用,通过适配器转化,将本来不兼容的两个组件可以通过适配器转换一起工作。