一什么是适配器模式?
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 电压!
来源: http://blog.csdn.net/qq_37923253/article/details/79285342