适配器设计模式

基本概念

 适配器模式:将一个类的接口转换成客户希望的另一个接口。适配器模式让那些接口不兼容的类可以一起工作

  Adapter Pattern:Convert the interface of a class into another interface clients expect.Adapter lets classes work together that couldn't otherwise because of incompatible interface.

  解释:适配器模式好比一个电源适配器,生活中房间内的电压是220v,但是你的很多用电器就不是220v,比如电脑、手机等等,这是需要电源适配器来调节电压,使用电源适配器充电的过程就相当于适配器模式。

UML图

     

解释

(1)目标(Target)角色:这就是所期待得到的接口。注意:由于这里讨论的是类适配器模式,因此目标不可以是类。

(2)源(Adapee)角色:现在需要适配的类。

(3)适配器(Adaper)角色:适配器类是本模式的核心。适配器把源接口转换成目标接口。显然,这一角色不可以是接口,而必须是具体类。

实例

     目标(Target)角色

package cn.itcast.sortdemo;
/**
 * 用户期待的接口
 * @author wjc
 *
 */
public interface Sortable {
	/**
	 * 在Adaper中会扩展的功能
	 */
	public void sort();
}

 源(Adapee)角色

package cn.itcast.sortdemo;

/**
 * Adapee
 * @author wjc
 *
 */
public abstract class ASort {
	
	protected  int arr[];
	/**
	 * 在Adaper中会复用的功能
	 * @param a
	 * @param b
	 */
	public void swap(int a,int b){
		int t = arr[a];
		arr[a] = arr[b];
		arr[b] = t;
	}
}

适配器(Adaper)角色

package cn.itcast.sortdemo;
/**
 * 适配器类是本模式的核心。
 * 适配器把源接口转换成目标接口。
 * @author wjc
 *
 */
public class SelectionSort extends ASort implements Sortable {

	public int a[] = {4,2,6,14};
	int t;
	
	SelectionSort(){
		super.arr = a;
	}
	
	/**
	 * 选择排序
	 */
	@Override
	public void sort() {
		// TODO Auto-generated method stub
		for(int i = 0;i<a.length-1;i++){
			int k = i;
			for(int j = i+1;j<a.length;j++){
				if(a[k]>a[j]){
					k = j;
				}
			}
			if(k != i){
				t = a[k];
				a[k] = a[i];
				a[i] = t;
			}
		}
	}
	/*
	public static void main(String[] args) {
		SelectionSort sel = new SelectionSort();
		sel.sort();
		for(int i = 0;i<4;i++){
			System.out.println(sel.a[i]);
		}
	}*/
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值