【设计模式】适配器模式的实现--------java

23 篇文章 0 订阅
22 篇文章 0 订阅

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

动机:将一些现存的对象放在新的环境中时,即利用现有对象的良好实现,又能满足新的应用环境所要求的接口。
有两种适配器模式:
类适配器模式:适配器与适配者之间是继承(或实现)关系。
对象适配器模式:适配器与适配者之间是关联关系。

1.对象适配器模式:
在这里插入图片描述
客户端要调用的是request()方法,而适配者Adaptee没有该方法,但是客户端需要的功能specificRequest()方法能实现。

package computer;

public class Test {
	public static void main(String[] args) {
		Target target=new Adapter();
		
		target.request();
	}
}

//客户所期待的接口,可以是具体的类也可以是抽象的类或接口
class Target{
	public void request() {
		System.out.println("普通请求");
	}
}

//需要适配的类
class Adaptee{
	public void specificRequest() {
		System.out.println("特殊请求");
	}
}

//适配器类(通过在内部包装一个Adaptee对象,把源接口转换为目标接口)
class Adapter extends Target{
	//简历私有的Adaptee对象,关联关系
	private Adaptee adaptee=new Adaptee();
	
	public void request() {
		//把调用request()方法变为调用SpecificRequest()方法
		adaptee.specificRequest();
	}
}

2.类适配器模式:
在这里插入图片描述

package computer;

public class Test {
	public static void main(String[] args) {
		ITarget target=new Adapter();
		
		target.request();
	}
}

//客户所期待的接口
interface ITarget{
	void request();
}

//需要适配的类
class Adaptee{
	public void specificRequest() {
		System.out.println("特殊请求");
	}
}

//适配器类
class Adapter extends Adaptee implements ITarget{
	public void request() {
		//把调用request()方法变为调用SpecificRequest()方法
		this.specificRequest();
	}
}

应用场景:希望复用一些现存的类,但是接口又与复用环境不一致的情况。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值