适配器(一)
单项适配器模式:
原接口:packagecom.jerry.design.adapter1.imp;
?
publicinterfaceInterfaceA {
?
publicvoidtestA();
?
}
?
接口实现类:
?
packagecom.jerry.design.adapter1.impl;
?
importcom.jerry.design.adapter1.imp.InterfaceA;
?
publicclassImplAimplementsInterfaceA{
?
@Override
publicvoidtestA() {
?
System.out.println(" i am do something as InterfaceA!");
?
}
?
}
?
目标接口:
?
packagecom.jerry.design.adapter1.imp;
?
publicinterfaceInterfaceB {
?
publicvoidtestB();
?
}
?
目标接口实现类:
?
?
packagecom.jerry.design.adapter1.impl;
?
importcom.jerry.design.adapter1.imp.InterfaceA;
importcom.jerry.design.adapter1.imp.InterfaceB;
?
publicclassImplBimplementsInterfaceB{
?
privateInterfaceAimplA;
?
publicImplB(InterfaceA implA){
?
this.implA= implA;
}
@Override
publicvoidtestB() {
?
implA.testA();
?
}
?
}
?
测试方法:
?
packagecom.jerry.design.adapter1.client;
?
importcom.jerry.design.adapter1.imp.InterfaceA;
importcom.jerry.design.adapter1.imp.InterfaceB;
importcom.jerry.design.adapter1.impl.ImplA;
importcom.jerry.design.adapter1.impl.ImplB;
?
publicclassTest {
?
publicstaticvoidmain(String[] args) {
?
InterfaceA implA = (InterfaceA)newImplA();
?
InterfaceB implB = (InterfaceB)newImplB(implA);
?
implB.testB();// i am do something as InterfaceA!
}
?
}
?
总结:原接口转换为目标接口