适配器(Adapter)模式:将一个类的接口转换为另一个接口,使得原来不兼容的类相互兼容。适配器模式分为:类适配器和对象适配器模式,前者的耦合度比后者要高,并且类适配器通过继承来完成适配,对象适配器则是通过关联来完成。

    优点:

    1. 通过适配器可以更加透明的调用目标接口
    2. 复用现存的类,而无需修改太多
    3. 解耦适配者和目标类,解决了二者接口不一致问题

    缺点:

    1. 需要结合系统业务考虑,会增加复杂性
    2. 降低了代码的可读性,适配器过多反而会使代码变得凌乱

    结构:

    1. 目标对象:用户期待的连接口,适配器类即将要进行适配的抽象类或接口;
    2. 适配者: 可以是内部的类或服务,也可以是外部对象或服务。
    3. 适配器:可以是类或接口,是作为具体适配者类的中间类来使用;

    类适配器示例:

    这一实现使用了继承机制: 适配器同时继承两个对象的接口,但是由于JAVA是单继承语言,所以需要配合接口去做

    1. public static void main(String[] args) {
    2. Target target = new Adapter();
    3. target.request();
    4. }
    5. // 目标接口
    6. interface Target{
    7. void request();
    8. }
    9. // 适配者
    10. static class Adaptee {
    11. public void specificRequest(){
    12. System.out.println("适配者");
    13. }
    14. }
    15. // 适配器
    16. static class Adapter extends Adaptee implements Target{
    17. @Override
    18. public void request() {
    19. // 可以在这里进行自定义的一些适配操作
    20. specificRequest();
    21. }
    22. }

    对象适配器示例:

    实现时使用了构成原则: 适配器实现了其中一个对象的接口, 并对另一个对象进行封装。 下面列举了一个电压适配的案例:我国居民用电为220V,手机充电一般只需要5V,所以需要将220V转换为5V

    1. public class AdapterDemo {
    2. public static void main(String[] args) {
    3. AdapterAC220 ac110 = new AdapterAC220();
    4. String ac = ac110.outputDC5V(new AC220V());
    5. System.out.println(ac); // 5V
    6. System.out.println(ac110.outputDC5V(new AC110V())); //电压异常
    7. }
    8. // 电压输出接口
    9. interface AC{
    10. String output();
    11. }
    12. // 110V电压
    13. static class AC110V implements AC{
    14. @Override
    15. public String output() {
    16. return "110V";
    17. }
    18. }
    19. // 220V电压
    20. static class AC220V implements AC{
    21. @Override
    22. public String output() {
    23. return "220V";
    24. }
    25. }
    26. // 适配器
    27. interface Adapter {
    28. // 比较 电压与适配器是否匹配
    29. boolean support(AC ac);
    30. // 转换电压
    31. String outputDC5V(AC ac);
    32. }
    33. // 110V 适配器
    34. static class AdapterAC110 implements Adapter{
    35. @Override
    36. public boolean support(AC ac) {
    37. return ac.output().equals("110V");
    38. }
    39. @Override
    40. public String outputDC5V(AC ac) {
    41. if (!this.support(ac)){
    42. return "电压异常";
    43. }
    44. return "5V";
    45. }
    46. }
    47. // 220V 适配器
    48. static class AdapterAC220 implements Adapter{
    49. @Override
    50. public boolean support(AC ac) {
    51. return ac.output().equals("220V");
    52. }
    53. @Override
    54. public String outputDC5V(AC ac) {
    55. if (!this.support(ac)){
    56. return "电压异常";
    57. }
    58. return "5V";
    59. }
    60. }
    61. }