【设计模式】(十三)--结构型模式--适配器模式

【设计模式】(十三)–结构型模式–适配器模式

适配器模式定义

Convert the interface of a class into another interface clients expect. Adapter lets classes work together that couldn`t otherwise because of incompatible interface.

意思是:讲一个类的接口变换成客户端所期待的另一个接口,从而使原本因为接口不匹配而无法在一起工作的两个类能在一起工作。
适配器模式一般有3个要素:

  • Target 支持的新接口
  • Adapter 将调用转发给Adaptee的适配器类
  • Adaptee 需要适配的旧代码

适配器模式的有点

  • 1、可以让任何两个没有关联的类一起运行。 、
  • 2、提高了类的复用。
  • 3、增加了类的透明度。
  • 4、灵活性好。

适配器模式的使用场景

  • 对已经在线上运行的系统进行拓展时,已有类的功能已存在但是和预期功能又出入时,可以通过适配器进行转化,转成符合目标要求的可以使用的类

简单的实现

类图
在这里插入图片描述
实现

public class CookerAdapter extends Wok implements FryingPan {
    @Override
    public void fry() {
        super.cook();
        System.out.println("开始煎食物");
    }

    public static void main(String[] args) {
        FryingPan fryingPan = new CookerAdapter();
        fryingPan.fry();
    }
}
/**
 * 炒锅
 */
public class Wok {
    public void cook() {
        System.out.println("开始烹饪");
    }
}
/**
 * 煎锅
 */
public interface FryingPan {
    void fry();
}

执行结果
在这里插入图片描述
实现解读
有一个Wok,通过适配实现了煎锅的功能。

原创文章 29 获赞 41 访问量 944

猜你喜欢

转载自blog.csdn.net/lovesunren/article/details/105872115