其他分享
首页 > 其他分享> > 适配器模式(Adapter)

适配器模式(Adapter)

作者:互联网

应用场景
以前开发的系统存在满足新系统功能需求的类,但其接口和新系统的接口不一致
使用第三方提供的组件,但组件接口定义和自己要求的接口定义不同

 

关键:适配器类继承适配者类或者拥有适配者类对象的引用

 

定义:将一个类的接口转换成客户希望的另外一个接口,使得原本由于接口不兼容而不能一起工作的那些类能一起工作

 

目标接口(Target):当前系统期待的接口,可以是抽象类或接口
适配者(Adaptee)
适配器(Adapter)

 

类适配器模式

//适配者类
class Adaptee {
	public void specificRequest() {
		System.out.println("适配者中业务代码");
	}
}

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

//适配器类
class Adapter extends Adaptee implements Target {
	public void request() {
		specificRequest();
	}
}

  

对象适配器模式

//适配者类
class Adaptee {
	public void specificRequest() {
		System.out.println("适配者中业务代码");
	}
}

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

//适配器类
class Adapter implements Target {
	private Adaptee adaptee;
	public Adapter(Adaptee adaptee) {
		this.adaptee = adaptee;
	}
	public void request() {
		adaptee.specificRequest();
	}
}

  

 

模式扩展:双适配器模式

//适配者接口
interface Adaptee {
	public void specificRequest();
}

//适配者接口实现类
class AdapteeImpl implements Adaptee {
	public void specificRequest() {
		System.out.println("适配者中业务代码");
	}
}

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

//目标接口实现类
class TargetImpl implements Target {
	public void request() {
		System.out.println("目标代码被调用");
	}
}

//双向适配器
class TwoWayAdapter implements Target,Adaptee {
	private Target target;
	private Adaptee adaptee;
	public TwoWayAdapter(Target target) {
		this.target = target;
	}
	public TwoWayAdapter(Adaptee adaptee) {
		this.adaptee = adaptee;
	}

	public void request() {
		adaptee.specificRequest();
	}
	public vodi specificRequest() {
		target.request()
	}
}

  

 

标签:Adapter,Target,适配,适配器,模式,public,void,接口,Adaptee
来源: https://www.cnblogs.com/tang321/p/14750437.html