jeudi 14 février 2019

Proxy pattern java?

Having the next classes:

public class WeatherInformationServiceInterface{

   public double getTemperature(Date date, City city);

 }



public class WeatherInformationService implements WeatherInformationServiceInterface{

   @Override
   public double getTemperature(Date date, City city){

      //Depending on system configuration you will get this information from 
       //jsonservice or a xml service

        if("JSONService".equals(configurationVariable)){
           //call JSONService
        }else if ("XMLService".equals(configurationVariable)){
           //call XMLService
         }

   }


}

My thoughts of this design is poor because:

  • If in the future another service is added to the system(RMI service for example to get the temperature), I will have to modify this class and this violates the OPEN/CLOSE principle
  • This is not real bussiness logic, I mean, evaluate if I have to call a JSON service or XMl service

My alternative design would be like this:

public class WeatherInformationService implements WeatherInformationServiceInterface{

       private WeatherInformationProxyService proxyService;

       @Override
       public double getTemperature(Date date, City city){    
         return proxyService.getTemperature(Date date, City city);    
       }


    }




public class WeatherInformationProxyService implements WeatherInformationServiceInterface{

       @Override
       public double getTemperature(Date date, City city){

          //Depending on system configuration you will get this information from 
           //jsonservice or a xml service

            if("JSONService".equals(configurationVariable)){
               //call JSONService
            }else if ("XMLService".equals(configurationVariable)){
               //call XMLService
             }

       }


    }

The second design would be better because:

  • You focus on real business logic in the class WeatherInformationService and you delegate the proxy logic to WeatherInformationProxyService, so this would comply the SRP(Single responsability principle) and then OPEN/CLOSE principle
  • If you have to add other other possible service to get the
    temperature, you dont have to modify the WeatherInformationService
    class, just WeatherInformationProxyService

The second design:

  • would be a PROXY pattern or similar? What do you think?
  • I dont like the fact that I have to modify the WeatherInformationProxyService if I want to add another service where to get the temperature from(this violates the OPEN/CLOSE principle). Any ideas?

Thanks

Aucun commentaire:

Enregistrer un commentaire