适配器模式
定义:将一个类转换成客户希望看到的另一个接口,使得原本由于接口不兼容而不能一起工作的那些类可以一起工作。简单来说:你现在有一个A的对象,但是现在需要B接口的对象,通过适配器模式可将A伪装成一个B的对象,达到目的,A的对象、B接口在功能上要类似。核心便是转化二字。
角色:目标接口,适配器,被适配接口
分类:有对象适配器和类适配器两种。类适配器是采用多重继承的方式,使适配器同事继承目标接口和被适配接口。
对象适配器则是适配器实现目标接口,同时拥有一个被适配接口的对象,当client需要调用目标接口方法时,则通过调用被适配接口的对象来完成任务。
示例代码:
/** * 目标接口 * @author sky * */ public interface GoodStudent { public void hardWorking(); } /** * 被适配者接口 * @author sky * */ public interface BadStudent { public void lazyWorking(); } /** * 被适配子类 * @author sky * */ public class Jon implements BadStudent { @Override public void lazyWorking() { System.out.println("学习一分钟"); } } /** * 适配器类,将一个坏学生,包装成好学生 * @author sky * */ public class Adapter implements GoodStudent { private BadStudent badStudent; public Adapter(BadStudent bStudent){ badStudent = bStudent; } @Override public void hardWorking() { for (int i = 0; i < 10; i++) { //坏学生要付出10倍的努力 badStudent.lazyWorking(); } } } /** * 测试类 * @author sky * */ public class Test { private GoodStudent goodStudent; public Test(GoodStudent gStudent){ goodStudent = gStudent; } public void testWork(){ goodStudent.hardWorking(); } public static void main(String[] args) { BadStudent badStudent = new Jon(); Adapter adapter = new Adapter(badStudent); Test test = new Test(adapter); test.testWork(); } }