适配器模式

1、适配器模式:把一个类的接口变换成客户端所期待的另一种接口,从而使原本接口不匹配而无法在一一起工作的两个类能够在一起工作。
2.适配器模式的两种形式
适配器adapter
适配者adaptee:需要适配的类
类适配器模式:适配器与适配者之间是继承(或实现)关系;
对象适配器模式:适配器与适配者之间是关联关系。
3.适配器模式结构图:在这里插入图片描述
4.适用情况:
在以下各种情况下使用适配器模式
(1)系统需要使用现有的类,而此类的接口不符合系统的需要。
(2)想要建立一个可以重复使用的类,该类可能与其它不相关的类或不可预见的类( 即那些接口可能不一定兼容的类)协同工作。
(3)对对象适配器而言)在设计里,想使用一些已经存在的子类,但是不可能对每一个子类都进行适配。对象适配器可以适配它们的父类接口。

//Target(这是客户所期待的接口)
class Target{
	public void Request() {
		System.out.println("普通请求!");
	}
}
//Adaptee(需要适配的类)
class Adaptee{
	public void SpecificRequest() {
		System.out.println("特殊请求!");
	}
}
class Adapter extends Target{
	private Adaptee adaptee=new Adaptee();
	public void Request() {
		adaptee.SpecificRequest();
	}
}
public class Main {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Target target=new Adapter();
		target.Request();
	}

}
interface ITarget{
	  default void Request() {
	}
}

//Adaptee(需要适配的类)
class Adaptee{
	public void SpecificRequest() {
		System.out.println("特殊请求!");
	}
}
class Adapter extends  Adaptee implements ITarget{
	public void Request() {
		this.SpecificRequest();
	}
}
public class Main {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		ITarget target=new Adapter();
		target.Request();
	}

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值