设计模式之适配器模式

适配器在生活中是一种很常见的一种东西,在国内买个手机欧版手机,充电器的插头和国内的插座不匹配,商家会为你提供一个转接头来适配,方能正常使用。中间的转接口就可看做是适配器。适配器模式就是类似的一个过程。
充电器是说明适配器模式的一个常用的例子,在此我也来借鉴一下。将欧式插头转到中式
 
 1 package com.cnblogs.ipolaris.adapter.test;
 2 
 3 public class CPlug {
 4         public String adapterSocket(){
 5               System. out .println("我是中式插头" );
 6                return "中式插头" ;
 7        }
 8 }
 9 
10 package com.cnblogs.ipolaris.adapter.test;
11 
12 public class EPlug {
13         public String adapterSocket(){
14               System. out .println("我是欧式插头" );
15                return "欧式插头" ;
16        }
17 
18        
19 }
20 
21 package com.cnblogs.ipolaris.adapter.test;
22 
23 public class PlugAdapter extends EPlug {
24        CPlug cplug ;
25         public PlugAdapter(CPlug cplug){
26                this .cplug = cplug;
27        }
28         public String adapterSocket() {
29                return cplug .adapterSocket();
30        }
31        
32        
33 }
34 
35 
36 package com.cnblogs.ipolaris.adapter.test;
37 
38 public class PhoneClient {
39 
40         /**
41         * @param args
42         */
43         public static void main(String[] args) {
44                //我们现在手上有个欧版HTC,要为手机充电,只有一个欧式的插头
45                //我们要把它适配成一个中式的充电器,即让他提供中式接口
46                //加上中式转接的欧式插头就可以插在国内的插座上了
47               EPlug eplug = new PlugAdapter( new CPlug());
48               System. out .println(eplug.adapterSocket());
49               
50        }
51 
52 }

 

posted @ 2012-09-12 00:09  iPolaris  阅读(242)  评论(0编辑  收藏  举报