zoukankan      html  css  js  c++  java
  • Adapter (适配器模式)

    适配器模式:

    将一个类的接口转换成客户希望的另外一个接口。Adapter模式使得原本由于接口不兼容而不能一起工作的那些类可以一起工作。

    有两种适配器模式:

    1)类适配器 (通过继承的方式)

    2)对象适配器 (采取对象组合的模式)

    -------------------------- 类适配器 -----------------------------

    Target.java

    [java] view plain copy
    1. package com.adapter ;  
    2.   
    3. public interface Target  
    4. {  
    5.     public void method() ;  
    6.   
    7. }  

    被适配器类

    Adaptee.java

    [java] view plain copy
    1. package com.adapter ;  
    2.   
    3. public class Adaptee  
    4. {  
    5.     public void method2()  
    6.     {  
    7.         System.out.println("Adapter-->method2()") ;  
    8.     }  
    9. }  

    适配器类 Adapter.java

    [java] view plain copy
    1. package com.adapter ;  
    2.   
    3. public class Adapter extends Adaptee implements Target  
    4. {  
    5.     public void method()  
    6.     {  
    7.         super.method2() ;//或者this.method2() ;  
    8.     }  
    9. }  

    Client.java

    [java] view plain copy
    1. package com.adapter ;  
    2.   
    3. public class Client  
    4. {  
    5.     public static void main(String[] args)  
    6.     {  
    7.         Target t = new Adapter() ;  
    8.         t.method() ;  
    9.     }  
    10. }  

    -------------------------- 对象适配器 -----------------------------

    Target.java

    [java] view plain copy
    1. package com.adapter ;  
    2.   
    3. public interface Target  
    4. {  
    5.     public void method() ;  
    6.   
    7. }  

    被适配器类

    Adaptee.java

    [java] view plain copy
    1. package com.adapter ;  
    2.   
    3. public class Adaptee  
    4. {  
    5.     public void method2()  
    6.     {  
    7.         System.out.println("Adapter-->method2()") ;  
    8.     }  
    9. }  

    适配器类 Adapter.java

    [java] view plain copy
    1. package com.adapter ;  
    2.   
    3. public class Adapter implements Target  
    4. {  
    5.     private Adaptee adaptee;  
    6.       
    7.     public Adapter(Adaptee adaptee)  
    8.     {  
    9.         this.adaptee = adaptee ;  
    10.     }  
    11.   
    12.     public void method()  
    13.     {  
    14.         this.adaptee.method2() ;  
    15.     }  
    16. }  

    Client.java

    [java] view plain copy
    1. package com.adapter ;  
    2.   
    3. public class Client  
    4. {  
    5.     public static void main(String[] args)  
    6.     {  
    7.         Adaptee adaptee = new Adaptee() ;  
    8.         Target t = new Adapter(adaptee) ;  
    9.         t.method() ;  
    10.     }  
    11. }  
  • 相关阅读:
    iOS 字典实现原理
    IOS中armv7,armv7s,arm64以及i386和x86_64讲解
    SDWebImage源码解析
    iOS Runtime的消息转发机制
    二叉树的遍历
    LINUX 常用命令 ps 详解
    LINUX 文件权限详解
    LINUX查看内存使用情况 free
    PHP isset() empty() isnull() 的区别
    PHP unset()函数销毁变量 但没有实现释放内存
  • 原文地址:https://www.cnblogs.com/hoobey/p/5294392.html
Copyright © 2011-2022 走看看