1.定义
适配器模式(Adapter Pattern)是指将一个类的接口转为客户期望的另一个接口,使原本的接口不兼容的类可以一起工作.
属于结构型设计模式
2.适用场景
1.已经存在的类,方法和需求不匹配
2.适配器模式不是软件设计阶段考虑的设计模式,是随着软件维护,由于不同产品,不同厂家造成功能类似而接口不同的情况下的解决方案
image.png
/**
* Description:220V交流电
*
* @date 2019-05-27 19:22
*/
public class AC220 {
public int outputAC220(){
int output = 220;
System.out.println("输出电流:"+output+"V");
return output;
}
}
/**
* Description:5V直流电
*
* @date 2019-05-27 19:24
*/
public interface DC5 {
int outputDC5V();
}
/**
* Description:变压器
*
* @date 2019-05-27 19:26
*/
public class PowerAdapter implements DC5{
private AC220 ac220;
public PowerAdapter(AC220 ac220) {
this.ac220 =ac220;
}
@Override
public int outputDC5V() {
return ac220.outputAC220()/44;
}
}
网友评论