java设计模式6 适配器模式

来源:互联网 发布:淘宝店铺起名字 编辑:程序博客网 时间:2024/06/06 12:25

适配器 就是讲以有的类通过适配器转化为我们需要的类型。适配器起到了中间作用


如图所示,适配器的作用就像是充电器一样 ,手机充电需要的是5v电压,但是家里插座出来的电压220V  手机适配器就是将其转换为5V的过程

public class Mobile  {      /**      * 充电      * @param power       */      public void inputPower(V5Power power)      {          int provideV5Power = power.provideV5Power();          System.out.println("手机(客户端):我需要5V电压充电,现在是-->" + provideV5Power + "V");      }  }  


/**  * 提供5V电压的一个接口  * @author zhy  *  */  public interface V5Power  {      public int provideV5Power();  }  
public class V220Power  {      /**      * 提供220V电压      * @return      */      public int provideV220Power()      {          System.out.println("我提供220V交流电压。");          return 220 ;       }  }  

下面我们需要一个适配器,完成220V转5V的作用:

/**  * 适配器,把220V电压变成5V  * @author zhy  *  */  public class V5PowerAdapter implements V5Power  {      /**      * 组合的方式      */      private V220Power v220Power ;            public V5PowerAdapter(V220Power v220Power)      {          this.v220Power = v220Power ;      }        @Override      public int provideV5Power()      {          int power = v220Power.provideV220Power() ;          //power经过各种操作-->5           System.out.println("适配器:我悄悄的适配了电压。");          return 5 ;       }         }  



最后测试,我们给手机冲个电:

public class Test  {      public static void main(String[] args)      {          Mobile mobile = new Mobile();          V5Power v5Power = new V5PowerAdapter(new V220Power()) ;           mobile.inputPower(v5Power);      }  }  


0 0
原创粉丝点击