java—是否值得使用适配器设计模式而不是对现有接口或类进行更改?

kokeuurv  于 2021-07-12  发布在  Java
关注(0)|答案(0)|浏览(229)

我正在研究适配器设计模式,发现我们可以允许我们与不兼容的接口协作。
现在假设,我在stackoverflow上找到了这个例子。

public interface IWetherFinder {
    public double getTemperature(String cityName);
}

class WeatherFinder implements IWetherFinder{
   @Override
   public double getTemperature(String cityName){
     return 40;
   }
}

interface IWeatherFinderClient
{
   public double getTemperature(String zipcode);
}  

public class WeatherAdapter implements IWeatherFinderClient {

    @Override
    public double getTemperature(String zipcode) {

        //method to get cityname by zipcode 
        String cityName = getCityName(zipcode);

        //invoke actual service
        IWetherFinder wetherFinder = new WeatherFinder();
        return wetherFinder.getTemperature(cityName);
    }

    private String getCityName(String zipCode) {
        return "Banaglore";
    }
}

在这种情况下,我们不能再向现有接口添加一个方法,如下所示。

public interface IWetherFinder {
    public double getTemperature(String cityName);
    public double getTemperatureByZipcode(String zipCode);
}

class WeatherFinder implements IWetherFinder{
   @Override
   public double getTemperature(String cityName){
    // some logic to get temp by city
     return 40;
   }

   @Override
   public double getTemperatureByZipcode(String zipCode){
    String city = getCityName(zipCode);
   //some logic to get the temp by city name
     return 40;
   }

   private String getCityName(String zipCode) {
        return "Banaglore";
    }

}

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题