适配器模式(Adapter模式)

将一个类的接口转换为客户希望的另外一个接口

适配器分为类适配器模式和对象适配器模式(前者应用较少)

适配器模式中主要包括三个角色:

(1)目标接口 :当前系统业务所期待的接口

(2)适配者类:现存的接口

(3)适配器类:转换器,将适配者接口转化为目标接口

其实是旧的接口希望通过适配器类,实现适配者类中的功能,成为一个新的接口

旧的接口,没有适配者中的功能(只有request方法)

新的接口,有适配者中的功能(千方百计想能够调用specificRequest方法)

 1.类适配器模式实现:

 

//目标接口
interface Target
{
    public void request();
}
//适配者类
class Adaptee
{
    public void specificRequest()
    {       
        System.out.println("适配者中的业务代码被调用!");
    }
}
//适配器类
//适配器类继承适配者类,而且实现目标接口(这意味着适配器类需要实现目标接口里的request方法)
//再加上继承适配者类,所以适配器类中有两个方法:request方法和specificRequest方法
class ClassAdapter extends Adaptee implements Target
{
    public void request()
    {
        specificRequest();
    }
}
//客户端代码
public class ClassAdapterTest
{
    public static void main(String[] args)
    {
        System.out.println("类适配器模式测试:");
        Target target = new ClassAdapter();
      //此时Target接口就不止一个request方法了,而是和适配器类一样也有
      //request和specificRequest两个方法了
        target.request();
    }
}

2.对象适配器模式

 

Adapter适配器类实现了旧目标接口,所以必须重写request函数

Adapter适配器虽然只有request函数,但是它的request函数里调用了一个适配者类对象的specificRequest方法,所以还是可以调用适配者类中的specificRequest方法

 

//目标接口
interface Target
{
    public void request();
}
//适配者接口
class Adaptee
{
    public void specificRequest()
    {       
        System.out.println("适配者中的业务代码被调用!");
    }
}
//适配器类
class Adapter implements Target
{
    private Adaptee adaptee;
    public Adapter(Adaptee adaptee)
    {
        this.adaptee=adaptee;
    }
    public void request()
    {
        adaptee.specificRequest();
    }
}
//客户端代码
public class Test
{
    public static void main(String[] args)
    {
        System.out.println("对象适配器模式测试:");
        Adaptee adaptee = new Adaptee();
        Target target = new Adapter(adaptee);
        target.request();
    }
}

 简洁版:

​
//目标接口
interface Target
{
    public void request();
}
//适配者接口
class Adaptee
{
    public void specificRequest()
    {       
        System.out.println("适配者中的业务代码被调用!");
    }
}
//适配器类
class Adapter implements Target
{
    
    public void request()
    {
      核心这句,在request函数里面调用一个适配者类对象的specificRequest方法

        adaptee.specificRequest();
    }
}
//客户端代码
public class Test
{
    public static void main(String[] args)
    {
        Adaptee adaptee = new Adaptee();
        Target target = new Adapter(adaptee);
        target.request();
    }
}

​

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值