适配器模式: 将一个接口转换为客户所需要的另一个接口,解决的问题是:使得原本不兼容而不能统一工作、不能统一管理的那些类可以在一起工作、可以进行统一管理。
普通模式:
1. 逐个输出
package Adapter;
public interface ICooker {
String cook();
}
package Adapter;
public class QjdCooker implements ICooker{
@Override
public String cook() {
return "烤制美味烤鸭";
}
}
package Adapter;
public interface IProgramer {
public String programer();
}
package Adapter;
public class JdProgramer implements IProgramer{
@Override
public String programer() {
return "编写高效程序";
}
}
package Adapter;
public class MyTest {
public static void main(String[] args) {
//普通方式
ICooker qjdCooker = new QjdCooker();
IProgramer jdProgramer = new JdProgramer();
System.out.println(qjdCooker.cook());
System.out.println(jdProgramer.programer());
}
2. 一个适配器:
package Adapter;
public interface IWorkerAdapter {
String work(Object worker);
}
//Object 保证所有类均适合
package Adapter;
public class WorkerAdapter implements IWorkerAdapter {
@Override
public String work(Object worker) {
String workContent = "";
if(worker instanceof ICooker){
workContent = ((ICooker)worker).cook();
}
if((worker instanceof IProgramer)){
workContent = ((IProgramer)worker).programer();
}
return workContent;
}
Object [] workers = {qjdCooker,jdProgramer};
//循环每个工种对象,让每个工种对象在适配器中逐个进行匹配
IWorkerAdapter adapter = new WorkerAdapter();
for(Object worker:workers){
System.out.println(adapter.work(worker));
}
3. 多个适配器
IWorkerAdapter:
package adapter;
public interface IWorkerAdapter {
String work(Object worker);
// 判断当前适配器是否支持指定的工种对象
boolean supports(Object worker);
}
CookerAdapter:
package adapter;
public class CookerAdapter implements IWorkerAdapter {
@Override
public String work(Object worker) {
return ((ICooker)worker).cook();
}
@Override
// 判断当前适配器是否支持指定的工种对象
public boolean supports(Object worker) {
return (worker instanceof ICooker);
}
}
TeacherAdapter:
package adapter;
public class TeacherAdapter implements IWorkerAdapter{
@Override
public String work(Object worker) {
return ((ITeacher)worker).teach();
}
@Override
public boolean supports(Object worker) {
return worker instanceof ITeacher;
}
}
MyTest:
/*MyTest*/
public class MyTest {
public static void main(String[] args){
ICooker lcCooker = new LcCooker();
ITeacher sjzTeacher = new SjzTeacher();
Object[] workers = new Object[] {lcCooker,sjzTeacher};
for(Object worker:workers){
IWorkerAdapter adapter = getAdapter(worker);
System.out.println(adapter.work(worker));
}
}
private static IWorkerAdapter getAdapter(Object worker) {
List<IWorkerAdapter> adapters = getAllAdapters();
for(IWorkerAdapter adapter : adapters)
if(adapter.supports(worker))
return adapter;
return null;
}
private static List<IWorkerAdapter> getAllAdapters() {
List<IWorkerAdapter> adapters = new ArrayList<>();
adapters.add(new CookerAdapter());
adapters.add(new TeacherAdapter());
return adapters;
}
}