首页 > 技术文章 > 适配器模式

imfjj 2017-11-09 15:18 原文

官方理解:适配器模式(Adapter Pattern)是作为两个不兼容的接口之间的桥梁。这种类型的设计模式属于结构型模式,它结合了两个独立接口的功能。

小坏理解:安卓线可以充电安卓机,苹果线可以充电苹果机,如果要实现这两种机型什么都可以充电怎么做呢,当然就做一个双接口的充电器,一头安卓,一头苹果机,这就是所谓的适配

场景与代码:之前只有一个安卓线充电器,现在要兼容一下苹果机的

步骤一:充电接口

public interface charge {
  // 根据telephone来选择型号
   public void play(String Type, String telephone);
}

  

 步骤二:苹果充电   (其实如果考虑到有其他类型手机,这里可以再写成接口)

public class AppleCharge {
   public void charge(){
  System.out.println(“充电”);
}
}

  

  

步骤三:创建适配器:
public class ChargeAdapter implements charge{
  AppleCharge appleCharge;
   AppleCharge ChargeAdapter()
  {
    appleCharge=new AppleCharge();
  } 
  public void charge( String telephone) 

  {
    System.out.println(“充电”+telephone);
  }
}

  

 

 步骤四:创建一个双接口充电器充电

public class andCharge implements charge
{
  ChargeAdapter chargeAdapter;
   public void play(String Type, String telephone){
    if(telephone=="and")
    {
       System.out.println(“还是按照以前安卓机一样充电”);
    }
    if(telephone=="apple")
    {
      chargeAdapter=new ChargeAdapter();
      chargeAdapter.charge();
    }
  }
}
}

  

这里推荐个网址还可以:http://www.runoob.com/design-pattern/adapter-pattern.html,我也是参考过来的

推荐阅读