Menu
CoddyTech

Despacho basado en interfaces

Lección 41 de 48 del curso C# para desarrolladores de Python de Coddy.

Quienes llaman a métodos en Python suelen confiar en el nombre del método mediante tipado pato. C# usa el contrato explícito INotifier y realiza el envío a través de este. El enrutador debe usar el objeto proporcionado en lugar de crear un notificador específico, para que las nuevas implementaciones sigan siendo sustituibles.

Una función basada en una interfaz puede aceptar implementaciones no relacionadas que cumplan el mismo contrato. Llama al miembro de la interfaz en lugar de alternar entre tipos concretos. Este diseño permite que quien llama inyecte una implementación de prueba o un nuevo notificador sin cambiar el enrutador. En esta lección no se contacta con ningún servicio.

Referencia de Python

class EmailNotifier:
    def send(self, message):
        return "email:" + message
notifier = EmailNotifier()
print(notifier.send("ok"))

Declaraciones auxiliares de C#

interface INotifier { string Send(string message); }
class EmailNotifier : INotifier { public string Send(string message) { return "email:"+message; } }

Instrucciones de C# dentro de Main

INotifier notifier = new EmailNotifier();
Console.WriteLine(notifier.Send("ok"));

Estos son fragmentos didácticos centrados en el tema. Los archivos del desafío incluyen envoltorios ejecutables completos; los fragmentos anteriores muestran las declaraciones e instrucciones pertinentes.

Salida de referencia:

email:ok

Salida de C#:

email:ok
challenge icon

Desafío

Fácil

Implementa EmailNotifier.Send, SmsNotifier.Send y Router.Deliver. El canal es email o sms. Cada notificador antepone su canal y dos puntos. Router delega en cualquier INotifier proporcionado por quien llama. Estos son modelos de formato de texto, no de mensajería de red real.

Edita los archivos C# desbloqueados. El archivo visible y bloqueado Main.cs lee las líneas descritas, llama a Exercise.Solve, verifica que la entrada no se haya modificado e imprime el resultado con un único salto de línea final. Mantén las API declaradas. No agregues un segundo Main ni imprimas mensajes de diagnóstico.

El lanzador bloqueado también prueba la API de ayuda o de clase exportada de forma independiente, no solo el contenedor Solve.

Pruébalo tú mismo

using System;
using System.Linq;
using System.Collections.Generic;
using System.Globalization;
public class Program {
static int I(string text) { return int.Parse(text,CultureInfo.InvariantCulture); }
static int[] Ints(string text) { return text.Length==0 ? new int[0] : text.Split(',').Select(I).ToArray(); }
static string[] Words(string text) { return text.Length==0 ? new string[0] : text.Split(','); }
static string Snapshot(object value) { if (value==null) return "<null>"; if (value is string) return (string)value; var sequence=value as System.Collections.IEnumerable; if (sequence!=null) { var items=new List<string>(); foreach (object item in sequence) items.Add(Snapshot(item)); return string.Join("|",items); } return Convert.ToString(value,CultureInfo.InvariantCulture); }
public static void Main() {
System.Threading.Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;
var rows = new List<string>(); string line; while ((line=Console.ReadLine()) != null) rows.Add(line);
string[] input=rows.ToArray();
var a0 = input[0]; string before0=Snapshot(a0);
var a1 = input[1]; string before1=Snapshot(a1);
if (new EmailNotifier().Send("") != "email:" || new SmsNotifier().Send("x") != "sms:x" || Router.Deliver(new ProbeNotifier(),"x") != "custom:x") throw new Exception("Notifier API");
var result = Exercise.Solve(a0,a1);
if (Snapshot(a0) != before0) throw new Exception("Input mutation");
if (Snapshot(a1) != before1) throw new Exception("Input mutation");
Console.WriteLine(result);
}
}
class ProbeNotifier : INotifier { public string Send(string message) { return "custom:"+message; } }
quiz iconPonte a prueba

Esta lección incluye un breve cuestionario. Empieza la lección para responderlo y registrar tu progreso.

Todas las lecciones de C# para desarrolladores de Python

Practica por tu cuenta: Compilador de C# online