适配器模式(Adapter Pattern)

本文详细介绍了适配器模式的概念,包括对象适配器和类适配器的区别,以及它们如何解决接口不兼容的问题,使不同类能够协同工作。通过具体的代码示例,展示了美国与中国电源插头接口适配的过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、定义:

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值