适配器模式(Adapter Pattern)
推荐一个很全面的博客:https://blog.csdn.net/zxt0601/article/details/52848004
定义:将一个类的接口转换成客户希望的另外一个接口,核心是兼容性,让原本因接口不匹配不能一起工作的两个类可以协同工作。其别名为包装器(Wrapper)。
何时使用(摘抄自runnoob):1、系统需要使用现有的类,而此类的接口不符合系统的需要。2、想要建立一个可以重复使用的类,用于与一些彼此之间没有太大关联的一些类,包括一些可能在将来引进的类一起工作,这些源类不一定有一致的接口。3、通过接口转换,将一个类插入另一个类系中。(比如老虎和飞禽,现在多了一个飞虎,在不增加实体的需求下,增加一个适配器,在里面包容一个虎对象,实现飞的接口。)
类图:二次整理时画
后期整理(springMVC中的适配器模式,真是巧妙~):https://www.cnblogs.com/tongkey/p/7919401.html
代码(这里采用一个很经典的demo):
1、现有的一个220V的电源:
package com.pat.Aadapter;
/**
* 这是一个220V的电源
* @author ZX
*
*/
public class PowerSource220V {
protected int v = 220;
//输出方法,输出220v
public int outPut() {
return v;
}
}
2、110V的接口,持有转换方法:
package com.pat.Aadapter;
/**
* 110V的接口,持有一个转换方法
* @author ZX
*
*/
public interface PowerSource110V {
//转换
int convert();
}
3、适配器对象:
package com.pat.Aadapter;
/**
* 适配器,继承了220v电源,并且实现了110v中的转换方法
* @author ZX
*
*/
public class Adapter extends PowerSource220V implements PowerSource110V{
@Override
public int convert() {
//调用父类方法
int outPutPower = outPut();
int convertPower =outPutPower/2;
return convertPower;
}
}
4、测试:
package com.pat.Aadapter;
public class Test {
public static void main(String[] args) {
//220V电源
PowerSource220V ps220 = new PowerSource220V();
int outPut = ps220.outPut();
System.out.println(outPut);
//使用适配器
Adapter ada = new Adapter();
int adapterOutPut = ada.convert();
System.out.println(adapterOutPut);
}
}
5:结果:
220
110
======================================================================
追加一个委托,JDK源码中非常常用:
1、随便找的一个类:
Executors.newCachedThreadPool(threadFactory);
2、点进去:
public static ExecutorService newCachedThreadPool(ThreadFactory threadFactory) { return new ThreadPoolExecutor(0, Integer.MAX_VALUE, 60L, TimeUnit.SECONDS, new SynchronousQueue<Runnable>(), threadFactory); }
3、下一层:
public ThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue, ThreadFactory threadFactory) { this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, threadFactory, defaultHandler); }
4、最终的构造方法:
public ThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue, ThreadFactory threadFactory, RejectedExecutionHandler handler) { if (corePoolSize < 0 || maximumPoolSize <= 0 || maximumPoolSize < corePoolSize || keepAliveTime < 0) throw new IllegalArgumentException(); if (workQueue == null || threadFactory == null || handler == null) throw new NullPointerException(); this.acc = System.getSecurityManager() == null ? null : AccessController.getContext(); this.corePoolSize = corePoolSize; this.maximumPoolSize = maximumPoolSize; this.workQueue = workQueue; this.keepAliveTime = unit.toNanos(keepAliveTime); this.threadFactory = threadFactory; this.handler = handler; }
5、这是我很喜欢的一种方式,面向需求变更编程啊哈哈。
================================================================
所有的源代码链接: