适配器模式

什么是适配器模式

适配器模式把一个类的接口变换成客户端所期待的另一种接口,从而使原本因接口不匹配而无法在一起工作的两个类能够在一起工作

适配器模式类图

1 //三相插座接口
2 public interface ThreePlugIf {
3     void powerWithThree();
4 }
1 public class GBTwoPlug {
2     public void powerWithTwo(){
3         System.out.println("二相电流供电");
4     }
5 }
 1 //二相转三相的插座适配器
 2 public class TwoPlugAdapter implements ThreePlugIf {
 3     private GBTwoPlug plug;
 4 
 5     public TwoPlugAdapter(GBTwoPlug plug){
 6         this.plug=plug;
 7     }
 8 
 9     @Override
10     public void powerWithThree() {
11         System.out.println("通过转换");
12         plug.powerWithTwo();
13     }
14 
15 }
1 //继承方式的插座适配器
2 public class TwoPlugAdapterExtends extends GBTwoPlug implements ThreePlugIf{
3     @Override
4     public void powerWithThree() {
5         System.out.println("借助继承适配器");
6         this.powerWithTwo();
7     }
8 }
 1 public class NoteBook {
 2     private ThreePlugIf plug;
 3 
 4     public NoteBook(ThreePlugIf plug){
 5         this.plug=plug;
 6     }
 7 
 8     //插座充电
 9     public void charge(){
10         plug.powerWithThree();
11     }
12 
13     public static void main(String[] args) {
14         GBTwoPlug two=new GBTwoPlug();
15         ThreePlugIf three=new TwoPlugAdapter(two);
16         NoteBook nb=new NoteBook(three);
17         nb.charge();
18 
19         three=new TwoPlugAdapterExtends();
20         nb=new NoteBook(three);
21         nb.charge();
22     }
23 
24 }
25 /*
26 通过转换
27 二相电流供电
28 借助继承适配器
29 二相电流供电
30  */

适配器模式的好处

1. 透明:通过适配器,客户端可以调用同一接口,因而对客户端来说是透明的,简单直接而又紧凑

2. 重用:复用了现存的类,解决了现存类和复用环境要求不一致的问题

3. 低耦合:把目标类和适配器类解耦,通过引入一个适配器类重用现有的适配者类,而无需修改原有代码(遵循开闭原则)

 

posted @ 2018-05-11 15:06  sakura1027  阅读(108)  评论(0编辑  收藏  举报