一、适配器模式: 适配器模式主要功能就是把一个类原来无法使用的接口转换为可以使用的接口; 类似苹果取消了3.5耳机接口,再配了一个转接器,这就是适配器; 二、类的适配器:
一、适配器模式:
适配器模式主要功能就是把一个类原来无法使用的接口转换为可以使用的接口;
类似苹果取消了3.5耳机接口,再配了一个转接器,这就是适配器;
二、类的适配器:
//通过继承被适配类,和实现标准接口来实现;
/** * 目标接口,或称为标准接口 **/ public interface Target { void newConnector(); } /** * 已存在的、具有特殊功能、但不符合我们既有的标准接口的类 **/ public class Adaptee { public void oldConnector() { System.out.println("3.5耳机口..."); } } /** * 适配器类,继承了被适配类,同时实现标准接口 **/ public class Adapter extends Adaptee implements Target { @Override public void newConnector() { this.oldConnector(); System.out.println("适配器,实现Lightning接口的适配..."); } } public class Client { public static void main(String[] args) { Target adapter = new Adapter(); //通过适配器调用特殊功能 adapter.newConnector(); } }
二、通过构造方法委托实现:
/** * 目标接口,或称为标准接口 **/ public interface Target { void newConnector(); } /** * 已存在的、具有特殊功能、但不符合我们既有的标准接口的类 **/ public class Adaptee { public void oldConnector() { System.out.println("3.5耳机口..."); } } /** * 适配器类 **/ public class Adapter implements Target { private Adaptee adaptee; public Adapter(Adaptee adaptee) { this.adaptee = adaptee; } @Override public void newConnector() { this.adaptee.oldConnector(); System.out.println("适配器,实现Lightning接口的适配..."); } } public class Client { public static void main(String[] args) { Target adapter = new Adapter(new Adaptee()); //通过适配器调用特殊功能 adapter.newConnector(); } }