适配器模式:是将一个类的接口转换成客户期望的另外一个接口。使得原本由于接口不兼容 而不能一起工作的那些类 可以一起工作。
适配器模式分为 对象适配器模式 和 类适配器模式。
首先看对象适配器模式:
UML
例子:
现在有一台笔记本NoteBook , 它的充电器是一个三口的,但是我现在只有一个二口的插板TwoPlug , 那么就需要一个三口的适配器(ThreePlugAdapter) 来将二口的插板转换成三口的插板供笔记本充电。
首先定义一个接口,表示 三口
/*三个口的插座或充电器* */
public interface ThreePlugInterface {
//充电
public void powerWithThree();
}
定义一个 二口插板的类
/*
* 两个插口的插座
* */
public class TwoPlug {
//充电
public void powerWithTwo()
{
System.out.println("使用两口插座充电");
}
}
* 两个插口的插座
* */
public class TwoPlug {
//充电
public void powerWithTwo()
{
System.out.println("使用两口插座充电");
}
}
接下来定义一个“三口插座适配器”,用来将”二口“插座转换成“三口插座”,显然该适配器需要实现”三口“接口
package com.immoc.pattern.adapter;
/*
* 二相转三相的插座适配器
*/
public class TwoPlugAdapter implements ThreePlugIf {
private GBTwoPlug plug;
public TwoPlugAdapter(GBTwoPlug plug){
this.plug = plug;
}
@Override
public void powerWithThree() {
System.out.println("通过转化");
plug.powerWithTwo();
}
}
/*
* 二相转三相的插座适配器
*/
public class TwoPlugAdapter implements ThreePlugIf {
private GBTwoPlug plug;
public TwoPlugAdapter(GBTwoPlug plug){
this.plug = plug;
}
@Override
public void powerWithThree() {
System.out.println("通过转化");
plug.powerWithTwo();
}
}
最后用来给笔记本充电
/*
* 笔记本
* 需要三口的充电器,但是现在只有两个插座的插板
* */
public class NoteBook {
//三口充电器,通过接口引用
private ThreePlugInterface threePlugIF;
public NoteBook(ThreePlugInterface threePlugIF)
{
this.threePlugIF=threePlugIF;
}
//使用三口的充电器充电
public void charge()
{
threePlugIF.powerWithThree();
}
public static void main(String[] args)
{
//两口的插座
TwoPlug twoPlug = new TwoPlug();
//因为没有三口的插座,需要通过两口的插座,和两口转三口的适配器来构造一个三口的插座
ThreePlugInterface threePlugIF = new ThreePlugAdapter(twoPlug);
new NoteBook(threePlugIF).charge();
}
}
* 笔记本
* 需要三口的充电器,但是现在只有两个插座的插板
* */
public class NoteBook {
//三口充电器,通过接口引用
private ThreePlugInterface threePlugIF;
public NoteBook(ThreePlugInterface threePlugIF)
{
this.threePlugIF=threePlugIF;
}
//使用三口的充电器充电
public void charge()
{
threePlugIF.powerWithThree();
}
public static void main(String[] args)
{
//两口的插座
TwoPlug twoPlug = new TwoPlug();
//因为没有三口的插座,需要通过两口的插座,和两口转三口的适配器来构造一个三口的插座
ThreePlugInterface threePlugIF = new ThreePlugAdapter(twoPlug);
new NoteBook(threePlugIF).charge();
}
}
运行结果
类适配器的UML图如下:
类适配器需要多重继承才能实现,因此在java中无法实现