设计模式——适配器模式(7)

一、写在前面

  • 代理模式
  • 适配器模式
  • 装饰者模式
  • 桥接模式
  • 外观模式
  • 组合模式
  • 享元模式

二、介绍

  • 如果去欧洲国家去旅游的话,他们的插座如下图最左边,是欧洲标准。而我们使用的插头如下图最右边的。因此我们的笔记本电脑,手机在当地不能直接充电。所以就需要一个插座转换器,转换器第1面插入当地的插座,第2面供我们充电,这样使得我们的插头在当地能使用。生活中这样的例子很多,手机充电器(将220v转换为5v的电压),读卡器等,其实就是使用到了适配器模式。
  • 将一个类的接口转换成客户希望的另外一个接口,使得原本由于接口不兼容而不能一起工作的那些类能一起工作。
    适配器模式分为类适配器模式和对象适配器模式,前者类之间的耦合度比后者高,且要求程序员了解现有组件库中的相关组件的内部结构,所以应用相对较少些。所以在这里,我们直接介绍对象适配器模式

三、对象适配器模式

  • 如果我们希望让A适配到B上,那么需要一个转换类C,C中聚合A的对象,并实现B的接口。C中实现的是A的方法。
  • 在client端,我们把C当成B的一个是实现类,并在构造C的时候,将A的实现类传入。
java 复制代码
//SD卡的接口
public interface SDCard {
	//读取SD卡方法
	String readSD();
	//写入SD卡功能
	void writeSD(String msg);
}
//SD卡实现类
public class SDCardImpl implements SDCard {
	public String readSD() {
		String msg = "sd card read a msg :hello word SD";
		return msg;
	}
	public void writeSD(String msg) {
		System.out.println("sd card write msg : " + msg);
	}
}
public class TFCardImpl implements TFCard {
	public String readTF() {
		String msg ="tf card read msg : hello word tf card";
		return msg;
	}
	public void writeTF(String msg) {
		System.out.println("tf card write a msg : " + msg);
	}
}
public class SDAdapterTF implements SDCard {
	private TFCard tfCard;
	public SDAdapterTF(TFCard tfCard) {
		this.tfCard = tfCard;
	}
	public String readSD() {
		System.out.println("adapter read tf card ");
		return tfCard.readTF();
	}
	public void writeSD(String msg) {
		System.out.println("adapter write tf card");
		tfCard.writeTF(msg);
	}
}
public class Client {
	public static void main(String[] args) {
		Computer computer = new Computer();
		SDCard sdCard = new SDCardImpl();
		System.out.println(computer.readSD(sdCard));
		System.out.println("------------");
		TFCard tfCard = new TFCardImpl();
		SDAdapterTF adapter = new SDAdapterTF(tfCard);
		System.out.println(computer.readSD(adapter));
	}
}
  • 适配器模式的使用场景为:
    • 以前开发的系统存在满足新系统功能需求的类,但其接口同新系统的接口不一致。
    • 使用第三方提供的组件,但组件接口定义和自己要求的接口定义不同。
相关推荐
昨天的猫1 小时前
《拒绝重复代码!模板模式教你优雅复用算法骨架》
后端·设计模式
L.EscaRC1 小时前
ArkTS分布式设计模式浅析
分布式·设计模式·arkts
Arva .2 小时前
责任链设计模式->规则树
设计模式
WKP94182 小时前
命令设计模式
设计模式
lapiii3586 小时前
[智能体设计模式] 第4章:反思(Reflection)
人工智能·python·设计模式
颜酱17 小时前
理解编程范式(前端角度)
设计模式
将编程培养成爱好19 小时前
C++ 设计模式《账本事故:当备份被删光那天》
开发语言·c++·设计模式·备忘录模式
FogLetter21 小时前
设计模式奇幻漂流:从单例孤岛到工厂流水线
前端·设计模式
guangzan1 天前
常用设计模式:代理模式
设计模式
西幻凌云1 天前
认识设计模式——单例模式
c++·单例模式·设计模式·线程安全·饿汉和懒汉