黑马程序员——对象、接口——适配器设计模式

------<a href="http://www.itheima.com" target="blank">Java培训、Android培训、iOS培训、.Net培训</a>、期待与您交流! -------

适配器设计模式:将不同接口的类转换成一个理想的接口,使该接口能兼容之前不同接口的类。


适用场合:1.系统需要使用已经存在的类,但是系统的接口与存在的类的接口不兼容,且不允许修改已经存在的类

 2. 想要建立一个新类,为了使其和其他没多大关系的类或者以后可能将要引进的类一起工作。


适配器模式一般有两种方法,一种是类适配器,还有一种是方法适配器。请看下例:

目标接口(Target):客户希望的接口,标准接口。

需要适配的类(Adaptee):需要被适配的类。

适配器(Adapter):将原接口转换成标准接口的类。


类适配器:

//已存在的,具有特殊功能,但不符合我们已有的标准接口的类;
class Adaptee {
	public void specificRequest(){
		System.out.println("specificRequest class");
	}
}

//目标接口,标准接口,用户希望的接口,能适合特殊功能的接口;
interface Target {
	public void request();
}

//原有类,只有普通功能
class ConcreteTarget implements Target {
	public void request (){
		System.out.println("common class");
	}
}

//适配器类,继承了被适配的类,同时实现标准接口;
class Adapter extends Adaptee implements Target {
	public void request() {
		super.specificRequest();
	}
}

public class testTarget {
	public static void main(String[] args) {
		Target concreteTarget = new ConcreteTarget();
		concreteTarget.request();
		Target adapter = new Adapter();
		adapter.request();
	}
}/*Output:
common class
specificRequest class
*/

------<a href="http://www.itheima.com" target="blank">Java培训、Android培训、iOS培训、.Net培训</a>、期待与您交流! -------

对象适配器:它不是使用多继承或者继承再实现的方式,而是使用直接关联,或者称为委托的方法。

class Adapter implements Target {
	private Adaptee adaptee;
	public Adapter( Adaptee adaptee){
		this.adaptee = adaptee;
	}
	public void request() {
		this.adaptee.specificRequest();
	}
}

public class testTarget {
	public static void main(String[] args) {
		Target concreteTarget = new ConcreteTarget();
		concreteTarget.request();
		Target adapter = new Adapter();
		adapter.request();
	}
}/*Output:
common class
specificRequest class
*/



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值