问题:用户家里现有一台洗衣机,使用交流电。现在用户想新购买一台录音机,录音机只能使用直流电。由于交流电公司只能供给用户家里的是交流电,因此,用户需要用适配器将交流电转化为直流电供录音机使用。
解析:问题是我们生活中常见到的问题,所以我们直接看代码
package face;
interface AlternateCurrent{ //交流电输出接口,被适配的接口,(String)101010为交流电,(String)111111为直流电
public String giveAlternateCurrent();
}
class PowerCompany implements AlternateCurrent{
@Override
public String giveAlternateCurrent() {
return "101010";
}
}
interface DirectCurrent{ //适配的目标接口,直流电输出接口
public String giveDirectCurrent();
}
class ElectricAdapter implements DirectCurrent{ //适配器,实现目标接口
AlternateCurrent out;
public ElectricAdapter(AlternateCurrent out){ //适配器构造函数:参数为交流电
this.out = out;
}
@Override
public String giveDirectCurrent() { //此方法将交流电适配成直流电
String m =out.giveAlternateCurrent();
StringBuffer s = new StringBuffer(m);
for(int i=0; i< s.length(); i++){
if(s.charAt(i)=='0'){
s.setCharAt(i, '1');
}
}
m = new String(s);
return m;
}
}
class Wash{ //家电洗衣机
private String name ="洗衣机";
public Wash(){
}
public String getName(){
return name;
}
public void work(AlternateCurrent s){
String str = s.giveAlternateCurrent(); //从交流电接口(被适配者接口)获取直流电
if(str.equals("101010")){ //洗衣机工作条件:直流电
System.out.println(name+"开始工作");
}else{
System.out.println(name+"没有工作");
}
}
}
class Recorder{ //家电录音机
private String name ="录音机";
public Recorder(){
}
public String getName(){
return name;
}
public void work(DirectCurrent s){
String str1 = s.giveDirectCurrent(); //从直流电接口(目标接口)获取直流电
if(str1.equals("111111")){ //录音机工作条件:直流电
System.out.println(name+"开始工作");
}else{
System.out.println(name+"没有工作");
}
}
}
public class Demo08 {
public static void main(String[] args) {
Wash wash = new Wash(); //实例化洗衣机
Recorder recorder = new Recorder(); //实例化录音机
AlternateCurrent aElectric = new PowerCompany(); //交流电公司提供交流电
wash.work(aElectric); //洗衣机插上交流电工作
DirectCurrent bElectric = new ElectricAdapter(aElectric); //适配器将交流电变成直流电
recorder.work(bElectric); //将录音机插上直流电工作
}
}