一、分类
- 类适配器模式
- 对象适配器模式
- 接口适配器模式
二、说明
- 适配器模式适合需要增加一个新接口的需求,在原接口与实现类基础上需要增加新的接口及方法。类似原接口只能method01方法,需求是增加method02方法,同时不再使用之前接口类。
新接口
public interface Targetable {
/**
*
*/
public void method01();
/**
*
*/
public void method02();
}
原接口实现类
public class Source {
public void method01() {
// TODO implement here
}
}
适配器类,用于实现新接口。继承原实现类,同时实现新接口。
public class Adapter extends Source implements Targetable {
/**
*
*/
public void method02() {
// TODO implement here
}
}
测试类
public class AdapterTest {
public static void main(String[] args) {
Targetable targetable = new Adapter();
targetable.method01();
targetable.method02();
}
}
源代码:
gitee.com