從應用的角度來看,適配器模式在代碼中應用的機會并不多。但從生活角度看,非常直觀生動,容易理解。去過美國的朋友都知道在去之前需要準備一個電源的轉換器,因為美國的插座格式和中國的不同,需要在中間做一個轉換,這是一個非常經典的適配器模式的例子。適配器模式就是把不適應的接口變成適應(或者叫做期望)的接口。
我原來有一個同事,名字叫做Garin,從小就會洗衣服,但是不會做飯;第一次找了個女朋友,結果人家女孩要求基本條件就是會洗衣做飯。
1 public interface IIdealBoyFriend {
2 public void doCooking();
3 public void doWashing();
4 }
5
一看不對呀,接口不匹配,怎么辦,簡單,適配吧:
1 public class BoyCanWashClothes {
2
3 private String name = null;
4
5 public void doWashing(){
6 System.out.println(name +" 費了九牛二虎之力總算洗完了衣服,好累啊。");
7 }
8
9 public BoyCanWashClothes(String name) {
10 super();
11 this.name = name;
12 }
13
14 }
只會做飯,不會洗衣服;適配以后:
1 public class PuteBoy extends BoyCanWashClothes implements IIdealBoyFriend{
2
3 public PuteBoy(String name) {
4 super(name);
5 }
6
7 @Override
8 public void doCooking() {
9 System.out.println(name+"找了個菜譜,倒騰了半天,終于把飯做熟了。");
10 }
11
12 }
妥了,學會做飯了。細心的同學可能發現,上面的例子其實是類的適配器模式,不但Garin能適配,Tom也能,James也可以。話說Garin用適配器模式搖身一變,會做飯了,但是由于缺乏修煉(還要花大量時間洗女朋友的臟衣服),飯菜味道不地道,女朋友和他吹了。又過了一段時間,Garin又找了個新的女朋友,還是得會洗衣做飯,而且規定衣服不能機洗,只能手洗。這回Garin該怎么辦呢,答案還是適配器模式,但是方法要變一變:
1 public class SmartBoy implements IIdealBoyFriend {
2
3 private String name = null;
4
5 public SmartBoy(String name) {
6 super();
7 this.name = name;
8 }
9
10 public void callHelp(BoyCanWashClothes worker){
11 this.worker = worker;
12 }
13
14 private BoyCanWashClothes worker = null;
15
16 @Override
17 public void doCooking() {
18 System.out.println(name+" 聚精會神做菜,滿滿的都是愛,飯菜非常可口。");
19 }
20
21 @Override
22 public void doWashing() {
23 System.out.print(name+" 叫了自己表弟來幫忙洗衣服,");
24 worker.doWashing();
25 }
26
27 }
這回對于洗衣服這活,Garin學精了,不親自動手了,叫了一個外援;結果由于節省了大量洗衣服時間,廚藝那是突飛猛進,女朋友非常滿意,成功進入下一階段。這個就是對象的適配器模式了,并不是所有人都有一個善于洗衣服的表弟。結果Garin通過歷練,順利從純情少男蛻變。
1 public class GirlFriendTest {
2
3 /**
4 * @param args
5 */
6 public static void main(String[] args) {
7 //使用類的代理模式
8 IIdealBoyFriend garin = new PuteBoy("Garin");
9 garin.doCooking();
10 garin.doWashing();
11 System.out.println("Garin成長中











");
12 //使用對象的代理模式
13 garin = new SmartBoy("Garin");
14 ((SmartBoy)garin).callHelp(new BoyCanWashClothes("Garin 表弟"));
15 garin.doCooking();
16 garin.doWashing();
17 }
18
19 }