适配器模式
适配器模式
定义:将一个类的接口转换成客户希望的另一个接口。Adapter模式使得原本由于接口不兼容而不能一起工作的那些类可以一起工作
对象适配器模式
比如有220v的电压 而手机只需要5v的电压,通过适配器模式,将220v适配到5v
//定义220v电压
public class Adaptee {
public int output220v(){
return 220;
}
}
//定义适配器接口
public interface Target {
int output5v();
}
//适配器接口实现类
public class Adapter implements Target{
private Adaptee adaptee;
public Adapter(Adaptee adaptee){
this.adaptee = adaptee;
}
@Override
public int output5v() {
int i = adaptee.output220v();
System.out.println(String.format( "原始电压: %d v ‐ > 输出电压: %d v ",i,5 ));
return 5;
}
}
使用:
public class Test {
public static void main(String[] args) {
Adaptee adaptee=new Adaptee();
Target target = new Adapter( adaptee );
target.output5v();
}
}
类适配器模式
public class Test {
public static void main(String[] args) {
Adpater adpater=new Adpater();
adpater.output5v();
}
}
class Adaptee{
public int output220v(){
return 220;
}
}
interface Target {
int output5v();
}
// Class Adapter
class Adpater extends Adaptee implements Target{
@Override
public int output5v() {
int i= output220v();
// ......
System.out.println(String.format( "原始电压: %d v ‐ > 输出电压: %d v ",i,5 ));
return 5;
}
}
应用场景
1.当你希望使用某些现有类,但其接口与您的其他代码不兼容时,请使用适配器类。
2.当你希望重用几个现有的子类,这些子类缺少一些不能添加到超类中的公共功能时,请使用该模式。
优点:
1.符合单一职责原则
2.符合开闭原则