5 适配器(Adapter)模式

本文详细介绍了适配器模式的概念及其实现方式,包括类适配器和对象适配器两种实现方法,并提供了具体的Java代码示例。

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

1. 含义

把一个类的接口变换成客户端所期待的另一种接口,从而使原本因接口不匹配而无法在一起工作的两个类能够在一起工作.

 

2. 类图

类适配

对象适配


3. 类代码

类适配

/**
 * 目标角色,期望得到的接口
 */
public interface Target {

	/**
	 * 这是源类也有的方法
	 */
	void sampleOperation1();

	/**
	 * 这是源类没有的方法
	 */
	void sampleOperation2();

}


/**
 * 源角色,需要适配的接口
 */
public class Adaptee {
	//源类含有的方法
	public void sampleOperation1() {
	};
}


/*
 * 适配器角色,把源接口转换成目标接口
 */
public class Adapter extends Adaptee implements Target {

	/**
	 * 由于源类没有这个方法,因此适配器类补充上这个方法
	 */
	public void sampleOperation2() {

	}

}


/*
 * 测试类
 */
public class Test {

	public static void main(String[] args) {
		Adapter a = new Adapter();
		a.sampleOperation1();
		a.sampleOperation2();
	}
}
 

对象适配

/*
 * 适配器角色,把源接口转换成目标接口
 */
public class Adapter implements Target {
        
        //把源类作为一个属性
	private Adaptee adaptee ;
	
	public Adapter(Adaptee adaptee) {
		super();
		this.adaptee = adaptee;
	}

	/**
	 * 源类有该方法,所有适配器类直接委派即可
	 */
	public void sampleOperation1() {
		adaptee.sampleOperation1();
	}

	public void sampleOperation2() {
	}
}


/*
 * 测试类
 */
public class Test {

	public static void main(String[] args) {
		
		Adapter a = new Adapter(new Adaptee());
		a.sampleOperation1();
		a.sampleOperation2();
	}
}
 

z

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值