适配器模式:
一个笔记本需要三相插口充电,然而现在只有双相电,需要为其创建适配器。
//提供双相电publicclassTwo(){
publicvoidchargewithTwo(){
System out println("用双相电充电")
}
}//三相电接口publicinterfaceThree(){
publicvoidchargewithThree();
}//适配器需要实现要转换的接口,并在构造函数中接收被转换的对象publicclassTwoToThreeAdapterimplementsThree(){private Two Two;
publicTwoToThreeAdapter(Two two){
this.two=two;
}
publicvoidchargewithThree(){
two.chargewithTwo();
}
}//笔记本publicclassNoteBook(){
private Three three;
publicNoteBook(Three three){
this.three=three;
}
publicvoidcharge(){
three.chargewithThree();
}
publicstaticmain(String[] args){
//只提供了双相电
Two two = new Two();
//将双相电转换为三相的接口
Three three = new TwoToThreeAdapter(two);
//为笔记本提供三相的接口
NoteBook book = new NoteBook(three);
//为笔记本充电
book.charge();
}
}