设计实现

适配器模式 往往用在新代码和老代码相互合作上。

首先以圆孔适配圆钉,圆孔不适配方钉为例,建立圆钉适配器,参数为方钉,从而使得圆孔也能适配方钉;圆钉和圆孔相当于老代码,方钉相当于新代码,适配器可以使得,新代码方钉和老代码圆孔相互合作。

代码实现

RoundPeg

包含有参无参构造函数,获取圆钉直径的方法。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public class RoundPeg {

private int radis;

public int getRadis() {
return radis;
}

public RoundPeg(int radis) {
this.radis = radis;
}

public RoundPeg() {
}
}

RoundHole

包含有参和无参构造函数,获取圆孔直径的方法,以及检查钉子适配圆孔的方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
public class RoundHole {
private int radis;

public RoundHole() {
}

public RoundHole(int radis) {
this.radis = radis;
}

public int getRadis() {
return radis;
}

public boolean fits(RoundPeg roundPeg){
if(this.radis>=roundPeg.getRadis()){
return true;
}
return false;
}
}

SquarePeg

包含有参和无参构造函数,获取宽度的方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
public class SquarePeg {
private int width;

private int length;

public int getWidth() {
return width;
}

public int getLength() {
return length;
}

public SquarePeg(int width, int length) {
this.width = width;
this.length = length;
}
}

SquarePegAdapter

方钉转圆钉适配器,继承圆钉,传参为方钉

1
2
3
4
5
6
7
8
9
10
11
12
13
14
public class SquarePegAdapter extends RoundPeg {
private SquarePeg squarePeg;

public SquarePegAdapter(SquarePeg squarePeg) {
this.squarePeg=squarePeg;
}

/*方钉到圆孔*/
@Override
public int getRadis(){
return (int) Math.sqrt(Math.pow((squarePeg.getWidth() / 2), 2) * 2);
}

}