1. 类适配器
- 客户端接口不满足要求
- 自定义一个适配器接口以及具体的适配器类,转换原来客户端接口
- 消费客户端时,客户端的实现不可见,具体是有适配器类进行工作
public class Test01 {
public static void main(String[] args) {
Buyer.buyHouse(new MiddleAdapter());
}
}
class Buyer {
public static void buyHouse(Adapter adapter) {
System.out.println(adapter.bargain());
}
}
class MiddleAdapter extends SourceHouseSeller implements Adapter {
@Override
public String bargain() {
int originalPrice = super.getPrice();
int finalPrice = originalPrice / 5;
return "ha, now the price is " + finalPrice + "rmb";
}
}
interface Adapter {
String bargain();
}
class SourceHouseSeller {
public int getPrice() {
return 100;
}
}
- 单继承原因,适配器类必须继承源客户端,这就要求适配器必须是一个接口
- 尽量减少继承
2. 对象适配器
public class Test01 {
public static void main(String[] args) {
Buyer.buyHouse(new MiddleAdapter());
}
}
class Buyer {
public static void buyHouse(Adapter adapter) {
System.out.println(adapter.bargain());
}
}
class MiddleAdapter implements Adapter {
private SourceHouseSeller sourceHouseSeller = new SourceHouseSeller();
@Override
public String bargain() {
int originalPrice = sourceHouseSeller.getPrice();
int finalPrice = originalPrice / 5;
return "ha, now the price is " + finalPrice + "rmb";
}
}
interface Adapter {
String bargain();
}
class SourceHouseSeller {
public int getPrice() {
return 100;
}
}
3. 缺省适配器模式
- 如果适配器接口中包含很多方法,但是在具体的适配器中并没有用到,这样就需要重写很多没用的方法
- 可以使用java 8 引入的接口默认实现方式,使得适配器中每个方法都有默认实现,具体的适配器需要用到哪个方法,就去覆盖哪个方法,省去了不必要方法的覆盖
public class Test01 {
public static void main(String[] args) {
Buyer.buyHouse(new MiddleAdapter());
}
}
class Buyer {
public static void buyHouse(Adapter adapter) {
System.out.println(adapter.bargain());
}
}
class MiddleAdapter implements Adapter {
private SourceHouseSeller sourceHouseSeller = new SourceHouseSeller();
@Override
public String bargain() {
int originalPrice = sourceHouseSeller.getPrice();
int finalPrice = originalPrice / 5;
return "ha, now the price is " + finalPrice + "rmb";
}
}
interface Adapter {
String bargain();
default int getAge() {
return -1;
}
default String getName(){
return "";
}
}
class SourceHouseSeller {
public int getPrice() {
return 100;
}
}