设计模式--适配器模式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(); 
    } 
 
} 

 

posted @ 2016-12-28 13:48  pinhole  阅读(291)  评论(0编辑  收藏  举报