基本概念
适配器模式:将一个类的接口转换成客户希望的另一个接口。适配器模式让那些接口不兼容的类可以一起工作
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]);
}
}*/
}