设计模式——适配器模式

一、应用场景

1、已存在的类,它的方法和需求不匹配的情况;

2、适配器模式不是软件设计阶段考虑的设计模式,是随着软件维护,由于不同产品、不同厂家造成功能类似而接口不相同情况下的解决方案;

二、适配器模式

将一个类的接口转化成客户端希望的目标类格式,使得原本不兼容的类可以在一起工作。

图 适配器说明

2.1 分类

2.1.1 类的适配器模式

图 类的适配器

/**
 * typeC插槽[目标类]
 */
public interface TypeCSlot {

    void runApplet();

}

/**
 * Usb 插头 【需适配的类】
 */
public class UsbPlug {

    void specialRun() {
        System.out.println("USB插头专属功能");
    }

}

/**
 * 第三方适配器
 */
public class ThirdAdapter extends UsbPlug implements TypeCSlot{

    @Override
    public void runApplet() {
        System.out.println("适配器操作");
        super.specialRun();
    }

}

public class Macbook {

    public static void main(String[] args) {
        System.out.println("Macbook 使用的是TypeC 接口,但是有个需求需要读取USB内容:");
        ThirdAdapter thirdAdapter = new ThirdAdapter();
        thirdAdapter.runApplet();
    }

}

 图 类的适配器运行结果

2.1.2 对象的适配器模式

图 对象的适配器

/**
 * RSA 加密接口
 */
public interface RSAEncryption {

   void encrypt(String str);

}

/**
 * 系统原先编写的RSA加密类
 */
public class RSAOrgEncryption {

    public void encryptValue(String str) {
        System.out.println("RSA加密:" + str);
    }

}

/**
 * RSA 适配器
 */
public class RSAAdapter implements RSAEncryption{

    private RSAOrgEncryption rsaOrgEncryption;

    public RSAAdapter(RSAOrgEncryption rsaOrgEncryption) {
        this.rsaOrgEncryption = rsaOrgEncryption;
    }

    @Override
    public void encrypt(String str) {
        System.out.println("适配器操作");
        rsaOrgEncryption.encryptValue(str);
    }

}

public class RSATest {

    public static void main(String[] args) {
        RSAOrgEncryption orgEncryption = new RSAOrgEncryption();
        RSAAdapter rsaAdapter = new RSAAdapter(orgEncryption);
        rsaAdapter.encrypt("123456");
    }

}

2.1.3 接口的适配器模式

一个接口中有多个抽象方法,但并不是所有方法我们都需要的,引入适配器模式,借助一个抽象类,该抽象类实现了该接口所有方法,然后新类继承该抽象类,重写我们需要的方法。

图 接口的适配器模式

/**
 * 电脑接口
 */
public interface Computer {

    void readBook();

    void writeCode();

    void playGames();

}

/**
 * 电脑抽象类
 */
public abstract class ComputerAbstract implements Computer{
    
    @Override
    public void readBook() {}

    @Override
    public abstract void writeCode();

    @Override
    public void playGames() {}
    
}

public class Macbook extends ComputerAbstract{
    
    @Override
    public void writeCode() {
        System.out.println("程序员最喜欢的电脑之一");
        System.out.println("屏幕特别好,系统特别流畅");
    }

    public static void main(String[] args) {
        Computer macbook = new Macbook();
        macbook.writeCode();
    }
    
}

 图 接口的适配器运行结果

三 优缺点

优点:

1)将目标类与适配类解耦;

2)增加了类的透明性和复用性,将具体实现封装在适配者类中,对于客户端来说是透明的;

缺点:

1)过多使用适配器,会让系统非常凌乱,不易整体进行把握;

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值