适配器模式
适配器模式(Adapter):将一个类的接口转换成客户希望的另外一个接口。Adapter模式使得原本由于接口不兼容而不能一起工作的那些类可以一起工作。
有两种适配器模式的实现方法,第一种是组合的方式(对象适配器模式): 适配器类将被适配者作为对象组合到该类中以修改目标接口包装被适配者。
第二种是继承的方式(类适配器模式): 实现目标对象类而继承被适配类,再重写被适配类从而适配目标类,此法的缺点是只能继承某个类(java是单继承的)那么就只能适配一个类,多个类的适配要重写多次。
对象适配器模式
1、一个目标类(接口)。
/**
* @Description: 三接口的插座,假如要使用插座的是笔记本电脑,也就是客户端所需要的接口
* @author: zxt
* @time: 2019年5月8日 下午8:47:36
*/
public interface ThreePlugInterface {
// 使用三相插座充电
public void powerWithThree();
}
2、一个已有的类(需要被适配的类)。
/**
* @Description: 这是一个二接口的电源,无法直接给笔记本电脑供电。即这是已经存在的类(接口),但是无法被客户端直接使用,需要被适配
* @author: zxt
* @time: 2019年5月8日 下午9:05:37
*/
public class GBTwoPlug {
public void powerWithTwo() {
System.out.println("使用二相电流供电!!!");
}
}
3、一个适配器类,将被适配者作为对象组合到该类中以修改目标接口。
/**
* @Description: 二相插座的适配器类,使得二相插座能够满足客户端的需求为三相电源供电
* @author: zxt
* @time: 2019年5月8日 下午9:12:50
*/
public class TwoPlugAdapter implements ThreePlugInterface {
// 使用组合的方式实现适配器类
private GBTwoPlug twoPlug;
public TwoPlugAdapter(GBTwoPlug twoPlug) {
this.twoPlug = twoPlug;
}
@Override
public void powerWithThree() {
System.out.print("组合的方式实现适配器类:");
twoPlug.powerWithTwo();
}
}
4、客户端的使用
/**
* @Description: 客户端的需求
* @author: zxt
* @time: 2019年5月8日 下午9:08:17
*/
public class Computer {
// 笔记本电脑需要一个三相的插座供电
private ThreePlugInterface plug;
public Computer(ThreePlugInterface plug) {
this.plug = plug;
}
// 使用插座充电
public void charge() {
plug.powerWithThree();
}
public static void main(String[] args) {
GBTwoPlug two = new GBTwoPlug();
ThreePlugInterface three = new TwoPlugAdapter(two);
Computer cp = new Computer(three);
cp.charge();
}
}
对于对象适配器的总结:
1、适配器的类中需要包含被适配器的对象作为成员变量,同时适配器类要实现目标接口。
2、被适配者产生对象作为参数传到适配器类中,因为适配器类是目标接口的实现类,所以目标接口通过适配器类产生对象,最后通过使用者类接收目标接口通过适配器类产生的对象作为参数来产生使用者类的对象。
3、因为使用者类中有目标接口的对象作为成员变量,从而通过使用者类的对象来调用使用者类中被适配好的方法(目标接口被适配器修改内容的方法)。
类适配器模式
1、适配器类
/**
* @Description: 二使用继承的方式实现适配器
* @author: zxt
* @time: 2019年5月8日 下午9:12:50
*/
public class TwoPlugAdapterExtends extends GBTwoPlug implements ThreePlugInterface {
@Override
public void powerWithThree() {
System.out.print("继承的方式实现适配器类:");
this.powerWithTwo();
}
}
2、客户端使用
public class Computer {
// 笔记本电脑需要一个三相的插座供电
private ThreePlugInterface plug;
public Computer(ThreePlugInterface plug) {
this.plug = plug;
}
// 使用插座充电
public void charge() {
plug.powerWithThree();
}
public static void main(String[] args) {
GBTwoPlug two = new GBTwoPlug();
ThreePlugInterface three = new TwoPlugAdapter(two);
Computer cp = new Computer(three);
cp.charge();
three = new TwoPlugAdapterExtends();
cp = new Computer(three);
cp.charge();
}
}
通过继承的方式成为类适配器。特点:通过多重继承不兼容接口,实现对目标接口的匹配,单一的为某各类而实现适配。
网友评论