Skip to content

Instantly share code, notes, and snippets.

@fernandezjose
Created January 8, 2018 02:07
Show Gist options
  • Save fernandezjose/c83726a18e0e18503ae231970d936d34 to your computer and use it in GitHub Desktop.
Save fernandezjose/c83726a18e0e18503ae231970d936d34 to your computer and use it in GitHub Desktop.
Adapter-pattern
using System;
using System.Net.Http;
namespace Vlao
{
class Program
{
static void Main(string[] args)
{
ICourierService courierDhl = new DHLWebServiceAdapter();
ICourierService servi = new ServiEntregaWebServiceAdapter();
ICourierService[] serviciosDeEntrega = new ICourierService[]{courierDhl, servi};
double quote=9999999;
int electedServiceIndex=0;
for (int i = 0; i < serviciosDeEntrega.Length; i++)
{
var tempQuote = serviciosDeEntrega[i].GetQuote();
if(quote>tempQuote)
{
quote = tempQuote;
electedServiceIndex = i;
}
}
serviciosDeEntrega[electedServiceIndex].EnviarPaquete();
serviciosDeEntrega[electedServiceIndex].RecogerPaquete();
}
}
public interface ICourierService {
double GetQuote();
void EnviarPaquete();
void RecogerPaquete();
void ConfirmarEntrega(int entregaID);
}
public class DHLWebServiceAdapter: ICourierService {
DHLWebService dHLWebService;
public DHLWebServiceAdapter()
{
dHLWebService = new DHLWebService();
}
void ICourierService.ConfirmarEntrega(int entregaID)
{
dHLWebService.ConfirmDelivery(entregaID);
}
void ICourierService.EnviarPaquete()
{
dHLWebService.SendPackage();
}
double ICourierService.GetQuote()
{
dHLWebService.GetQuote();
return 0;
}
void ICourierService.RecogerPaquete()
{
throw new NotImplementedException("DHL no ofrece este servicio.");
}
}
public class DHLWebService
{
HttpClient client;
public DHLWebService()
{
client = new HttpClient();
}
public double GetQuote()
{
var url = "dhl.com/api/getquote";
client.GetAsync(url);
return 0;
}
public void SendPackage()
{
var url = "dhl.com/api/sendPackage";
client.GetAsync(url);
}
public void ConfirmDelivery(int id)
{
var url = "dhl.com/api/confirmDelivery";
client.GetAsync(url);
}
}
public class ServiEntregaWebServiceAdapter : ICourierService
{
ServiEntregaWebService service;
public ServiEntregaWebServiceAdapter()
{
service = new ServiEntregaWebService();
}
void ICourierService.ConfirmarEntrega(int entregaID)
{
throw new Exception("Este tipo no confirma nada!");
}
void ICourierService.EnviarPaquete()
{
service.Enviar();
}
double ICourierService.GetQuote()
{
return service.Cotizacion();
}
void ICourierService.RecogerPaquete()
{
throw new NotImplementedException();
}
}
public class ServiEntregaWebService
{
HttpClient client;
public ServiEntregaWebService()
{
client = new HttpClient();
}
public double Cotizacion()
{
var url = "se.com/api/cotizacion";
client.GetAsync(url);
return 0;
}
public void Enviar()
{
var url = "se.com/api/enviarPaquete";
client.GetAsync(url);
}
public void RecogerPaquete()
{
// Recoger paquete.
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment