适配器模式用于解决接口不兼容问题。软件设计中,常常会出现要将一些"现存的对象"放到新的环境中,而新环境要求的接口是现对象不能满足的。
场景:有接口一,以及接口一的实现类;接口二,以及接口二的实现类。要让接口一下的类能去做接口二下的方法。(让二口插座能为三口电源充电)
用法:
1.定义接口一
public interface Interface1 {
public void Method1();
public void Method1(String type);
}
2.定义接口二
public interface Interface2 {
public void Method2();
}
3.创建接口二的实现类
public class Interface2impl implements Interface2{
@Override
public void Method2() {
// TODO Auto-generated method stub
System.out.println("执行接口2下的方法2");
}
}
4.创建接口一的适配器
public class Interface1Adapter implements Interface1{
Interface2 interface2 = new Interface2impl();
@Override
public void Method1() {
// TODO Auto-generated method stub
}
@Override
public void Method1(String type) {
// TODO Auto-generated method stub
}
public void MethodAdapter() {
// TODO Auto-generated method stub
interface2.Method2();
}
}
5.接口一的实现类
public class Interface1impl implements Interface1{
Interface1Adapter interface1Adapter = new Interface1Adapter();
@Override
public void Method1() {
// TODO Auto-generated method stub
System.out.println("执行接口1下的方法1");
}
@Override
public void Method1(String type) {
// TODO Auto-generated method stub
if (type.equalsIgnoreCase("method2")) {
interface1Adapter.MethodAdapter();
}
}
}
6.测试类
public class AdapterPatternTest {
public static void main(String[] args) {
Interface1 interface1impl = new Interface1impl();
interface1impl.Method1();
Interface1Adapter interface1Adapter = new Interface1Adapter();
interface1Adapter.MethodAdapter();
Interface1 interface1impl2 = new Interface1impl();
interface1impl2.Method1("method2");
}
}
7.输出
总结:用适配器实现原始接口(接口一),持有目标接口(接口二)的实例,动态执行接口二下的方法。主类中可以选择用接口一来判断性地执行接口二下的方法,或者直接调用适配器来执行。