# 定义
# 适配器是一种结构型设计模式, 它能使不兼容的对象能够相互合作。
适配器可担任两个对象间的封装器, 它会接收对于一个对象的调用, 并将其转换为另一个对象可识别的格式和接口。
# 结构
# 伪代码
# 示例
# 让方钉适配圆孔
# 1. 圆孔: adapter.RoundHole.java
package adapter;
public class RoundHole {
private double radius;
public RoundHole(double radius) {
this.radius = radius;
}
public double getRadius() {
return radius;
}
public boolean fits(RoundPeg roundPeg) {
return this.radius >= roundPeg.getRadius();
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
# 2. 圆钉: adapter.RoundPeg.java
package adapter;
public class RoundPeg {
private double radius;
public RoundPeg(){
}
public RoundPeg(double radius){
this.radius = radius;
}
public double getRadius() {
return radius;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
# 3. 方钉: adapter.SquarePeg.java
package adapter;
public class SquarePeg {
private double width;
public SquarePeg(double width) {
this.width = width;
}
public double getWidth() {
return width;
}
public double getSquare() {
return Math.pow(this.width, 2);
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
# 4. 方钉到圆孔的适配器: adapter.SquarePegAdapter.java
package adapter;
public class SquarePegAdapter extends RoundPeg {
private SquarePeg peg;
public SquarePegAdapter(SquarePeg squarePeg) {
this.peg = squarePeg;
}
@Override
public double getRadius() {
// Calculate a minimum circle radius, which can fit this peg.
return (Math.sqrt(Math.pow((peg.getWidth() / 2), 2) * 2));
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# 5. 客户端代码: adapter.Demo.java
package adapter;
public class Demo {
public static void main(String[] args) {
// Round fits round, no surprise.
RoundHole roundHole = new RoundHole(5);
RoundPeg roundPeg = new RoundPeg(5);
if(roundHole.fits(roundPeg)){
System.out.println("Round peg r5 fits round hole r5.");
}
SquarePeg smallSqPeg = new SquarePeg(2);
SquarePeg largeSqPeg = new SquarePeg(20);
// roundHole.fits(smallSqPeg); // Won't compile.
// Adapter solves the problem.
SquarePegAdapter smallSqPegAdapter = new SquarePegAdapter(smallSqPeg);
SquarePegAdapter largeSqPegAdapter = new SquarePegAdapter(largeSqPeg);
if (roundHole.fits(smallSqPegAdapter)) {
System.out.println("Square peg w2 fits round hole r5.");
}
if (!roundHole.fits(largeSqPegAdapter)) {
System.out.println("Square peg w20 does not fit into round hole r5.");
}
}
}
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
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
# 6. 输出结果
Round peg r5 fits round hole r5.
Square peg w2 fits round hole r5.
Square peg w20 does not fit into round hole r5.
1
2
3
2
3