适配器模式:
定义:适配器模式将某个类的接口转换成客户端期望的另一个接口表示,主的目的是兼容性,让原本因接口不匹配不能一起工作的两个类可以协同工作。
主要分为三类:类适配器模式、对象的适配器模式、接口的适配器模式。
使用场景:
1 系统需要使用现有的类,而这些类的接口不符合系统的需要。
2 想要建立一个可以重复使用的类,用于与一些彼此之间没有太大关联的一些类,包括一些可能在将来引进的类一起工作。
3 需要一个统一的输出接口,而输入端的类型不可预知。
类适配器模式:
Adapter类,通过继承 src类,实现 dst 类接口,完成src->dst的适配。充电器本身相当于Adapter,220V交流电相当于src,我们的目dst标是5V直流电。
我们现有的src类:
/**
* 介绍:src类: 我们有的220V电压
* 作者:zhangxutong
* 邮箱:zhangxutong@imcoming.com
* 时间: 2016/10/18.
*/
public class Voltage220 {
public int output220V() {
int src = 220;
System.out.println("我是" + src + "V");
return src;
}
}
我们想要的dst接口:
/**
* 介绍:dst接口:客户需要的5V电压
* 作者:zhangxutong
* 邮箱:zhangxutong@imcoming.com
* 时间: 2016/10/18.
*/
public interface Voltage5 {
int output5V();
}
适配器类:
/**
* 介绍:Adapter类:完成220V-5V的转变
* 通过继承src类,实现 dst 类接口,完成src->dst的适配。
* 作者:zhangxutong
* 邮箱:zhangxutong@imcoming.com
* 时间: 2016/10/18.
*/
public class VoltageAdapter extends Voltage220 implements Voltage5 {
@Override
public int output5V() {
int src = output220V();
System.out.println("适配器工作开始适配电压");
int dst = src / 44;
System.out.println("适配完成后输出电压:" + dst);
return dst;
}
}
Client类:
/**
* 介绍:Client类:手机 .需要5V电压
* 作者:zhangxutong
* 邮箱:zhangxutong@imcoming.com
* 时间: 2016/10/18.
*/
public class Mobile {
/**
* 充电方法
*
* @param voltage5
*/
public void charging(Voltage5 voltage5) {
if (voltage5.output5V() == 5) {
System.out.println("电压刚刚好5V,开始充电");
} else if (voltage5.output5V() > 5) {
System.out.println("电压超过5V,都闪开 我要变成note7了");
}
}
}
测试代码:
System.out.println("===============类适配器==============");
Mobile mobile = new Mobile();
mobile.charging(new VoltageAdapter());
输出:
===============类适配器==============
我是220V
适配器工作开始适配电压
适配完成后输出电压:5
电压刚刚好5V,开始充电
类图如下:
缺点:
/**
* 介绍:对象适配器模式:
* 持有 src类,实现 dst 类接口,完成src->dst的适配。 。以达到解决**兼容性**的问题。
* 作者:zhangxutong
* 邮箱:zhangxutong@imcoming.com
* 时间: 2016/10/18.
*/
public class VoltageAdapter2 implements Voltage5 {
private Voltage220 mVoltage220;
public VoltageAdapter2(Voltage220 voltage220) {
mVoltage220 = voltage220;
}
@Override
public int output5V() {
int dst = 0;
if (null != mVoltage220) {
int src = mVoltage220.output220V();
System.out.println("对象适配器工作,开始适配电压");
dst = src / 44;
System.out.println("适配完成后输出电压:" + dst);
}
return dst;
}
}