适配器(Adapter)模式

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

二,类的Adapter模式的结构:

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

三,示例代码

/**
 * 目标
 * 
 * @author Salmon
 * 
 */
public interface Target {
	public void request();
}

/**
 * 源
 * 
 * @author Salmon
 * 
 */
public class Adaptee {
	public void specificRequest() {
		System.out.println("Called SpecificRequest()");
	}
}

/**
 * 适配器
 * 
 * @author Salmon
 * 
 */
public class Adapter extends Adaptee implements Target {
	// Implements ITarget interface
	public void request() {
		// Possibly do some data manipulation
		// and then call SpecificRequest
		this.specificRequest();
	}
}

/**
 * 客户代码
 * 
 * @author Salmon
 * 
 */
public class Client {
	public static void Main(String[] args) {
		// Create adapter and place a request
		Target t = new Adapter();
		t.request();
	}
}

四,对象的Adapter模式的结构

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

目标(Target)角色:这是客户所期待的接口。目标可以是具体的或抽象的类,也可以是接口。
源(Adaptee)角色:需要适配的类。
适配器(Adapter)角色:通过在内部包装(Wrap)一个Adaptee对象,把源接口转换成目标接口。

五,示例代码

/**
 * 目标接口
 * @author Salmon
 *
 */
public interface Target {
	public void request();
}

/**
 * 源
 * @author Salmon
 *
 */
public class Adaptee {
	public void SpecificRequest() {
		System.out.println("Called SpecificRequest()");
	}
}

/**
 * 适配器
 * @author Salmon
 *
 */
public class Adapter implements Target {
	private Adaptee adaptee = new Adaptee();
	public void request() {
		// Possibly do some data manipulation
		// and then call SpecificRequest
		adaptee.SpecificRequest();
	}
}



/**
 * 客户端代码
 * 
 * @author Salmon
 * 
 */
public class Client {
	public static void main(String[] args) {
		// Create adapter and place a request
		Target t = new Adapter();
		t.request();
	}
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值