zoukankan      html  css  js  c++  java
  • 设计模式--适配器模式Adapter(结构型)

    一、适配器模式

    适配器模式的主要作用是在新接口和老接口之间进行适配。将一个类的接口转换成客户端期望的另外一个接口。其实适配器模式有点无赖之举,在前期设计的时候,我们就不应该考虑适配器模式,而应该通过重构统一接口。

    二、适配器模式分为类适配器模式和对象适配器模式

    类适配器模式:适配器使用多重继承对一个接口与另外一个接口进行匹配。

    对象适配器模式:适配器在新接口中利用已有类的实例来实现接口的匹配。

    三、UML图

    类适配器模式

    对象适配器模式

    四、示例

    类适配器模式

    package com.visionsky.DesignPattern; 
     
    interface Target { 
        void Request(); 
    } 
     
    class Adaptee { 
        void SpecificRequst() { 
            System.out.println("Adaptee's SpecificRequst"); 
        } 
    } 
     
    class Adapter extends Adaptee implements Target  
    { 
     
        @Override 
        public void Request() { 
             System.out.println("Adapter's Request"); 
              super.SpecificRequst(); 
        } 
     
    } 
     
    public class AdapterDemo { 
     
        /** 
         * @param args 
         */ 
        public static void main(String[] args) { 
            // TODO Auto-generated method stub 
            Target t=new Adapter(); 
            t.Request(); 
        } 
     
    } 

    对象适配器模式

    package com.visionsky.DesignPattern; 
     
    interface Target { 
        void Request(); 
    } 
     
    class Adaptee { 
        void SpecificRequst() { 
            System.out.println("Adaptee's SpecificRequst"); 
        } 
    } 
     
    class Adapter  implements Target  
    { 
     
        private Adaptee adaptee; 
        public Adapter() 
        { 
            this.adaptee=new Adaptee(); 
        } 
         
        @Override 
        public void Request() { 
             System.out.println("Adapter's Request"); 
             adaptee.SpecificRequst(); 
        } 
     
    } 
     
    public class AdapterDemo { 
     
        /** 
         * @param args 
         */ 
        public static void main(String[] args) { 
            // TODO Auto-generated method stub 
            Target t=new Adapter(); 
            t.Request(); 
        } 
     
    } 
  • 相关阅读:
    linux下apache(httpd)安装部署
    基于redis分布式缓存实现(新浪微博案例)
    python--字典
    django(四)
    django(三)
    django(二)
    django(一)
    053(八十)
    053(七十九)
    053(七十八)
  • 原文地址:https://www.cnblogs.com/justkong/p/6229185.html
Copyright © 2011-2022 走看看