设计模式的学习(7)适配器模式

本文详细介绍了适配器模式的概念,包括其作为类结构型模式和对象结构型模式的应用方式。通过具体的代码示例,展示了如何使用适配器模式解决接口不兼容的问题,使现有类能够与其他类协同工作。

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

适配器模式

适配器模式(Adapter Pattern)将一个接口转换成客户希望的另一个接口,使接口不兼容的那些类可以一起工作,其别名为包装器(Wrapper)。

适配器模式既可以作为类结构型模式,也可以作为对象结构型模式。常用作在不修改源代码的情况下让已经存在的类能和其他类一起使用。

根据适配器类和适配者类的关系,适配器模式可以分为以下两种:

  • 对象适配器模式(组合的方式)

  • 类适配器模式(继承的方式)
为什么

试想一下,如果我们不使用适配器模式,我们可以选择修改源码或者更改我们的目标接口。而修改源码或是更改接口很大的代价很大,甚至是我们根本就没有源码。就好像我们无法更换插座接口或是充电器的接头一样。

怎么做

由于适配器模式有多种,下面通过几个代码片段来分别学习一下:

  • 对象适配器模式 
  • 类适配器模式

945cbee48076820046bebfc34daa0f0d648.jpg

定义目标接口

/**
 * 目标接口
 * 
 */
public interface Target {
	void request();
}

定义适配者类

/**
 * 适配者类
 * 
 */
public class Adaptee {
	/**
	 * 客户期望使用的业务方法
	 */
	public void specificRequest() {
		System.out.println("Adaptee Specific request!");
	}

}

定义对象适配器类

/**
 * 适配器类(对象适配器模式实现)
 */
public class Adapter implements Target {

	// 以组合的方式关联适配者
	private Adaptee adaptee;

	public Adapter(Adaptee adaptee) {
		this.adaptee = adaptee;
	}

	public void setAdaptee(Adaptee adaptee) {
		this.adaptee = adaptee;
	}

	/**
	 * 对接口进行转换
	 */
	public void request() {
		adaptee.specificRequest();
	}
}

定义类适配器类

/**
 * 类适配器模式
 * 
 */
public class AdapterClass extends Adaptee implements Target {

	public void request() {
		specificRequest();
	}

}

创建请求

public class Main {
	public static void main(String[] args) {
		// 对象是配器模式
		Adaptee adaptee = new Adaptee();
		Target target = new Adapter(adaptee);
		target.request();
		// 类适配器模式
		Target target1 = new AdapterClass();
		target1.request();
	}
}

 

转载于:https://my.oschina.net/xiaoyoung/blog/2994140

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值