随笔 - 330,  文章 - 1,  评论 - 0,  阅读 - 9025

一、定义:

     通过增加一个新的适配器类来解决接口不兼容的问题,使得原本没有任何关系的类可以协同工作。即:将一个接口转换成客户希望的另一个接口,使接口不兼容的那些类可以一起工作,其别名为包装器(Wrapper)。

二、分类:

  1. 对象适配器
  2. 类适配器两种

三、关系:
    在对象适配器模式中,适配器与适配者之间是关联关系;
    在类适配器模式中,   适配器与适配者之间是继承(或实现)关系。

四、类适配器(主要使用继承方式来适配)

1、类适配器模式

AmericaPower.java(美国的电源头是三个脚的) 

package com.adapterModel.classAdapter;

public interface AmericaPower {
    public void threeStep();
}

 

 AmericaPower.java(美国电源插头的接口类)

package com.adapterModel.classAdapter;

public class APower implements AmericaPower {

    @Override
    public void threeStep() {
        System.out.println("我是三角的电源");
    }

}

ChinaPower.java(中国电源插头的接口类)



package com.adapterModel.classAdapter;

public interface ChinaPower {
    
    public void twoStep();

}

CPower.java(中国插头的具体实现类) 

package com.adapterModel.classAdapter;

public class CPower extends APower implements ChinaPower {

    @Override
    public void twoStep() {
        
        this.threeStep();

    }

}

测试类

package com.adapterModel.classAdapter;

public class Test {

    public static void main(String[] args) {
        ChinaPower chinaPower = new CPower();
        //插入两脚的电源线,可以适配三角的插头。
        chinaPower.twoStep();
        
    }
          
}

2、对象适配器

AmericaPower.java
package com.adapterModel.instanceAdapter;

public interface AmericaPower {
    public void threeStep();
}

APower.java

package com.adapterModel.instanceAdapter;
public class APower implements AmericaPower {

    @Override
    public void threeStep() {
        System.out.println("我是三角的电源");
    }

}

ChinaPower.java

package com.adapterModel.instanceAdapter; public interface ChinaPower { public void twoStep(); }

CPower.java(内有一个美国插头的实例对象)

package com.adapterModel.instanceAdapter;

public class CPower implements ChinaPower {
    
    private AmericaPower ap = new APower();

    @Override
    public void twoStep() {
        
        ap.threeStep();

    }

}

测试类

package com.adapterModel.instanceAdapter;

public class Test {

    public static void main(String[] args) {
        ChinaPower chinaPower = new CPower();
        //插入两脚的电源线,可以适配三角的插头。
        chinaPower.twoStep();
        
    }
}
posted on   vow007  阅读(4)  评论(0编辑  收藏  举报  
编辑推荐:
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

点击右上角即可分享
微信分享提示