三要素:
1,客户提供接口
2,现有的类
3,适配器
举例说明:
1,客户提供的接口
public interface ICalculate {
public int getResult(int x , int y);
}
2, 现有类
public class AddCalculate {
public int add(int x, int y){
return x+y;
}
}
3适配器的设计模式实现可分为两类:
(1), 类适配器:继承现有的类,并且实现客户提供的接口
public class Adapter extends AddCalculate implements ICalculate{
public int getResult(int x, int y) {
return add(x, y);
}
}
(2),对象适配器:
public class Adapter implements ICalculate{
private AddCalculate add ;
public Adapter(AddCalculate add){
this.add = add;
}
public int getResult(int x, int y) {
return add.add(x, y);
}
}
4,测试
public class Main {
public static void main(String args[]){
//class way
ICalculate calculate = new classWay.Adapter();
System.out.println(calculate.getResult(10, 20));
//object way
ICalculate calculate2 = new objectWay.Adapter(new AddCalculate());
System.out.println(calculate2.getResult(10, 20));
}
}