适配器模式把一个类的接口变成客户端所期待的另外一个接口,从而使本来不匹配而没法在一块儿工做的两个类可以在一块儿工做java
适配器模式分为两种,类适配器模式和对象适配器模式markdown
classDiagram Target <|.. Adapter Adaptee <|-- Adapter class Target{ <<interface>> +operation1() +operation2() } class Adapter{ +operation2() } class Adaptee{ +operation3() }
//Target 角色,须要5V电压
public interface FiveVolt{
int getVolt5();
}
//adaptee 角色,提供220V 电压
public class Vlot220{
pulic int getVlot220(){
return 220;
}
}
//adapter 角色,将220V 电压转换成5V 电压
public class VlotAdapter extends Vlot220 implements FiveVolt{
public int getVolt5(){
return 220to5Vlot();
}
private int 220to5Vlot(){
return 5;
}
}
//使用
public class Test{
public static void main(String[] args){
VlotAdapter adapter = new VlotAdapter();
adapter.getVolt5();
}
}
复制代码
classDiagram Target <|.. Adapter Adaptee <.. Adapter class Target{ <<interface>> +operation1() +operation2() } class Adapter{ +operation2() } class Adaptee{ +operation3() }
从类图上能够看出,对类适配器和象适配器的不一样主要是在Adapter 和 Adaptee 的关系上;前者是继承,后者是组合。spa
//adapter 角色
public class VoltAdapter implements FiveVolt{
Volt220 mVolt220;
public VoltAdapter(Volt220 adaptee){
mVolt220 = adaptee;
}
public int getVolt5(){
return 220to5Vlot();
}
private int 220to5Vlot(){
return 5;
}
}
//使用
public class Test{
public static void main(String[] args){
VlotAdapter adapter = new VlotAdapter(new Volt220());
adapter.getVolt5();
}
}
复制代码
这种实现方式直接将要被适配的对象床底到Adapter 中,使用组合的形式实现接口兼容的效果。这笔类适配器方式更灵活,它的另外一个好处是被适配对象中的方法不会被暴露出去,类适配器模式因为继承了被适配对象,所以被适配对象的方法在Adapter 类中也会有,这使得Adapter 类会多出一些奇怪的方法,用户使用成本较高。所以,对象适配器更为灵活、实用。code