适配器属于结构型模式,结构中包含目标,被适配者和适配器3种。
-
目标(Target):目标是一个接口,该接口是客户想使用的接口。
-
被适配者(Adaptee):被适配者是一个已存在的接口或抽象类,这个接口或抽象类需要被适配。
-
适配器(Adaptor):适配器是一个类,该类实现了目标接口并包含被适配者的引用,即适配器的职责是对被适配器接口(抽象类)与目标接口进行适配。
下面以直流电转交流电供收音机使用为例子
DirectCurrent.java//定义一个用户相使用的接口 public interface DirectCurrent { public String giveDirectCurrent();
}
AlternateCurrent.java
//定义交流电接口
public interface AlternateCurrent {
public String giveAlternateCurrent();
}
ElectricAdaptor.java
public class ElectricAdapter implements DirectCurrent {
//out是交流电输出
AlternateCurrent out;
ElectricAdapter(AlternateCurrent out){
this.out = out;
}
@Override
public String giveDirectCurrent() {
String m = out.giveAlternateCurrent();
StringBuffer str = new StringBuffer(m);
//使用StringBuffer对字符串进行修改,类的对象能够被多次的修改,并且不产生新的未使用对象。
for (int i=0;i<str.length();i++) {
if(str.charAt(i)=='0') {
str.setCharAt(i,'1');
}
}
m = new String(str);
return m;
}
}
Application.java
public class Application {
public static void main(String[] args) {
AlternateCurrent aElectric = new PowerCompany();
Wash wash = new Wash("电视机");
wash.turnon(aElectric);
Recoder recode = new Recoder("收音机");
DirectCurrent bElectric = new ElectricAdapter(aElectric);
recode.turnon(bElectric);
}
}
class PowerCompany implements AlternateCurrent{
@Override
public String giveAlternateCurrent() {
// TODO Auto-generated method stub
return "0101010";
}
}
class Wash{
String name;
// Wash(){
// name = "洗衣机";
// }
Wash(String s){
name = s;
}
public void turnon(AlternateCurrent a){
String s = a.giveAlternateCurrent();
System.out.println(name+"使用交流电"+s);
}
}
class Recoder{
String name;
// Recoder(){
// name = "录音机";
// }
Recoder(String s){
name = s;
}
public void turnon(DirectCurrent a) {
String s = a.giveDirectCurrent();
System.out.println(name + "使用直流电"+ s);
}
}
实验结果