情景讲解:
image.pngimage.png
需要对参数做一定的修改,进行适配

类适配器模式

image.png
示例代码
public class Adaptee { //**原接口
public void operation1() {
System.out.print(“ This is an existing method.”)
}
}
public interface Target { //**新接口,声明所有的方法
void operation1();
void operation2();
}
//**适配器类
public class Adapter extends Adaptee implements Target {
/ 类Adaptee不包含Operation2(),所以我们需要在这里实现它。 /
public void operation2() {
// **写代码实现此方法**
}
}
public class Client {
private static **Targetadp; // use the interface as type**

public static void main (String[] **args**){
adp = new Adapter();
adp.operation1();
adp.operation2();
}
}
在类适配器模式中,能否同时适配两个类
1.在C++中,这种设计是可以的,但是多重继承有时可能引入复杂性。
2.在Java中不允许这种设计,因为在Java中不允许多重继承

对象适配器模式

image.png
示例代码
public class **Adaptee** {
public void operation1() {
**System.out.println(“ operation 1 is in Adaptee**.”);
}
}
public interface Target**{
void operation1();
void operation2();
}
public class Adapter implements Target {
private Adaptee adaptee;
public Adapter(Adaptee adaptee) {//由参数传入
this.adaptee = adaptee; //adaptee对象
}
public void operation1() {
adaptee.operation1(); //调用
}
public void operation2()** {
// 写新代码
System.out.print(“ you need to write code for operation2 .”);
}
}

使用时机

  • 您希望使用现有的类,但其接口与您需要的接口不匹配
  • 您希望创建一个可重用的类,该类与具有不兼容接口的无关类协作
  • 在设计中,您需要更改许多子类的接口。在这种情况下,使用对象适配器。

在对象适配器模式中,能否同时适配两个类

更进一步讨论

适配器模式的应用主要体现在两个方面

  1. 改变接口
  2. 增加功能

这两个方面哪个是主要的呢**?
回答: 改变接口。实际上增加功能也可以看作是改变接口,因为增加了功能也就改变了接口。
类适配器模式和对象适配器模式之间的区别**

  • 在类适配器模式中,所有属性和方法都是继承的
  • 在对象适配器模式中,通常只选择一个或多个方法来拉入适配器类