创建需要适配的类,例如Triangle和Trapezoid类。 创建适配器类AreaAdapter,实现目标接口AreaCalculator,并持有需要适配的对象的引用。 在适配器类AreaAdapter中实现目标接口AreaCalculator的方法,通过调用需要适配的对象的方法,实现对该对象的适配。 在客户类Client中,通过创建适配器对象并传入需要适配的对象的引用,实现对需要适配对象的动态绑定,从而实现对新功能的调用。
时间: 2024-02-19 10:57:21 浏览: 10
好的,下面是一个简单的实现示例:
首先,定义需要适配的类Triangle和Trapezoid:
```java
public class Triangle {
private double base;
private double height;
public Triangle(double base, double height) {
this.base = base;
this.height = height;
}
public double getBase() {
return base;
}
public void setBase(double base) {
this.base = base;
}
public double getHeight() {
return height;
}
public void setHeight(double height) {
this.height = height;
}
public double getArea() {
return 0.5 * base * height;
}
}
public class Trapezoid {
private double top;
private double bottom;
private double height;
public Trapezoid(double top, double bottom, double height) {
this.top = top;
this.bottom = bottom;
this.height = height;
}
public double getTop() {
return top;
}
public void setTop(double top) {
this.top = top;
}
public double getBottom() {
return bottom;
}
public void setBottom(double bottom) {
this.bottom = bottom;
}
public double getHeight() {
return height;
}
public void setHeight(double height) {
this.height = height;
}
public double getArea() {
return 0.5 * (top + bottom) * height;
}
}
```
然后,定义目标接口AreaCalculator:
```java
public interface AreaCalculator {
double getArea();
}
```
接下来,定义适配器类AreaAdapter,实现目标接口AreaCalculator,并持有需要适配的对象的引用:
```java
public class AreaAdapter implements AreaCalculator {
private Triangle triangle;
private Trapezoid trapezoid;
public AreaAdapter(Triangle triangle) {
this.triangle = triangle;
}
public AreaAdapter(Trapezoid trapezoid) {
this.trapezoid = trapezoid;
}
@Override
public double getArea() {
if (triangle != null) {
return triangle.getArea();
} else if (trapezoid != null) {
return trapezoid.getArea();
} else {
throw new RuntimeException("Unsupported shape");
}
}
}
```
最后,在客户类Client中,通过创建适配器对象并传入需要适配的对象的引用,实现对需要适配对象的动态绑定,从而实现对新功能的调用:
```java
public class Client {
public static void main(String[] args) {
Ellipse ellipse = new Ellipse(2, 3);
AreaCalculator ellipseAdapter = new AreaAdapter(ellipse);
System.out.println("Ellipse area: " + ellipseAdapter.getArea());
Rectangle rectangle = new Rectangle(2, 3);
AreaCalculator rectangleAdapter = new AreaAdapter(rectangle);
System.out.println("Rectangle area: " + rectangleAdapter.getArea());
Triangle triangle = new Triangle(2, 3);
AreaCalculator triangleAdapter = new AreaAdapter(triangle);
System.out.println("Triangle area: " + triangleAdapter.getArea());
Trapezoid trapezoid = new Trapezoid(2, 3, 4);
AreaCalculator trapezoidAdapter = new AreaAdapter(trapezoid);
System.out.println("Trapezoid area: " + trapezoidAdapter.getArea());
}
}
```
输出结果如下:
```
Ellipse area: 18.84955592153876
Rectangle area: 6.0
Triangle area: 3.0
Trapezoid area: 7.5
```
可以看到,通过适配器模式,我们成功地将Triangle和Trapezoid类适配到了原有的面积计算程序中,实现了对新功能的调用。