1 定义:
适配器模式把一个类的接口变换成客户端所期待的另一种接口,从而使原本接口不匹配而无法在一起工作的两个类能够在一起工作
2 解决的问题
使接口不兼容的类可以在一起工作。
3 模式中的角色
1)目标接口(Target):客户所期待的接口。目标可以是具体的或抽象的类,也可以是接口。
2)需要被适配的类(Adaptee):被适配的角色
3)适配器(Adapter):通过包装一个需要适配的对象,把原接口转换成目标接口。
4 模式分类
类适配器模式和对象适配器模式。我也不懂。。。
例子:
看流程图吧:
看代码:
1.原来的类
/**
* 原来的类
* @author king
* @version 1.0
*/
public class Adaptee {
public void adapteeOption(){
System.out.println("this is a adaptee option !!!");
}
}
2. 适配接口
/**
*
* @Description:
* 适配接口
* @author king
* @version 1.0
*/
public interface Target {
public void option();
}
3. 适配类
/**
*
* @Description:
* 适配类
* @author king
* @version 1.0
*/
public class Adapter extends Adaptee implements Target {
//适配的方法
@Override
public void option() {
this.adapteeOption();
}
}
4. 运行一下
public class Run {
public static void main(String[] args) {
Target target = new Adapter();
//看看打印出来啥了
target.option();
}
}
运行结果:
this is a adaptee option !!!
另外推荐一个群,目前没多少人,主要是技术讨论,促进菜鸟成长:207974203