Java23种设计模式之-----适配器模式

一、什么是适配器模式?
Adapter模式也叫做适配器模式,是构造型模式之一,通过Adapter模式可以改变已有类(或外部类)的接口形式。
二、代码举例实现:
(1)、创建Current类

package com.renxin.adspter;

public class Current {
    public void user220V() {
        System.out.println("使用220V电压!");
    }
}

(2)、创建Adspter类并且继承Current

package com.renxin.adspter;

public class Adspter extends Current {

    public void user18V() {
        System.out.println("使用适配器!");
        this.user220V();
    }
}

(3)、创建测试类MainClass

package com.renxin.adspter;

public class MainClass {
    public static void main(String[] args) {

        //Current current = new Current();
        //current.user220V();

        Adspter adspter = new Adspter();
        adspter.user18V();
    }
}

控制台输出结果为:

使用适配器!
使用220V电压!

三、适配器模式应用场景
在大规模的系统开发过程中,我们常常碰到诸如以下这些情况:我们需要实现某些功能,这些功能已有还不太成熟的一个或多个外部组件,如果我们自己重新开发这些功能会花费大量时间,所以很多情况下会选择先暂时使用外部组件,以后再考虑随时替换。但是这样一来,会带来一个问题,随着对外部组件库的替换,可能需要对引用该外部组件的源代码进行大面积的修改,因此也极可能引入行的问题等等。如何最大限度的减低修改面呢?
Adapter模式就是针对这种类似需求而提出来的。
Adapter模式通过定义一个新的接口(对要实现的功能加以抽象),和一个实现该接口的Adapter(适配器)类来透明地调用外部组件。这样替换外部组件时,最多只要修改几个Adapter类就可以了,其他源代码都不会受影响。
四、适配器模式结构
适配器模式的结构分为两种:
第一种:通过继承实现Adapter
这里写图片描述
也就是上面举例的代码!
第二种:通过委让实现Adapter
这里写图片描述
代码实现:
(1)、创建Adapter2

package com.renxin.adspter;

public class Adapter2 {
    private Current current;

    public Adapter2(Current current) {
        this.current=current;
    }

    public void user18V() {
        System.out.println("使用适配器");
        this.current.user220V();
    }
}

(2)、修改测试类MainClass

package com.renxin.adspter;

public class MainClass {
    public static void main(String[] args) {

        //Current current = new Current();
        //current.user220V();

        //Adspter adspter = new Adspter();
        //adspter.user18V();

        Adapter2 adapter2 = new Adapter2(new Current());
        adapter2.user18V();
    }
}

控制台测试结果为:

使用适配器
使用220V电压!
  • 2
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值