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

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值