Adapter-适配器设计模式
1、类图展示
2、编码步骤
1、编写Shape抽象类
/**
* 定义抽象图形类
* @author SoftStar
*/
abstract class Shape {
private int x, y;
public Shape() {
}
public Shape(int x, int y) {
this.x = x;
this.y = y;
}
public void setLocation(int x, int y) {
this.x = x;
this.y = y;
}
public int[] getLocation() {
return new int[] { x, y };
}
abstract void display();
}
2、编写Point、Line、Sequare实体类
//Point类
public class Point extends Shape {
int x, y;
public Point() {
}
public Point(int x, int y) {
this.x = x;
this.y = y;
}
@Override
void display() {
System.out.println("A point [" + x + "," + y + "]");
}
}
//Line类
public class Line extends Shape {
int x, y;
public Line() {
}
public Line(int x, int y) {
this.x = x;
this.y = y;
}
@Override
void display() {
System.out.println("A Line [" + x + "," + y + "]");
}
}
//Sequare
public class Sequare extends Shape {
int x, y;
public Sequare() {
}
public Sequare(int x, int y) {
this.x = x;
this.y = y;
}
@Override
void display() {
System.out.println("A Sequare [" + x + "," + y + "]");
}
}
3、当想引用一个已存在的类的方法
//NewCircle实体类 [已存在]
public class NewCircle {
private int x, y;
public NewCircle() {
}
public NewCircle(int x, int y) {
this.x = x;
this.y = y;
}
public void setLocation() {
this.x = x;
this.y = y;
}
public int[] getLocation() {
return new int[] { x, y };
}
public void display() {
System.out.println("A NewCircle [" + x + "," + y + "]");
}
public void OtherMethod() {
System.out.println("Other Method");
}
}
4、创建适配器类
//Cicle适配器类
public class Circle extends Shape {
private NewCircle circle;
public Circle() {
circle = new NewCircle();
}
public Circle(int x, int y) {
circle = new NewCircle(x, y);
}
@Override
void display() {
circle.display();
}
}
5、测试类
//测试类
public class Main {
public static void main(String[] args) {
Shape shape = new Line(10, 10);
shape.display();
Shape shape2 = new Circle(5, 5);
shape2.display();
}
}
6、输出显示
A Line [10,10]
A NewCircle [5,5]
3、Adapter模式特征
意图: 是控制范围之外的一个原有对象与某个接口匹配。
解决方案: Adapter模式提供了具有所需接口的包装类。
参与者与协作者:
Adapter改变了Adapter的接口,是Adapter与Adapter的基类Target匹配。这样Client就可以使用Adapter了,好像他是Target类型。实现: 将原有类包含在另一个类之中。让包含类与需要的接口匹配,调用被包容的类的方法。
Adapter模式的通用结构图