samedi 24 avril 2021

Is it worthy to use adapter design pattern instead of making changes in existing interface or classes?

I was going through adapter design pattern, and found we can allow us to collaborate with incompatible interface.

Now suppose, I found this example on 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";
    }
}

Now in this case can't we add one more method to existing interface something Like below.

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";
    }

}

Aucun commentaire:

Enregistrer un commentaire