Menu
CoddyTech

インターフェースによるディスパッチ

Coddyの「C++開発者のためのC#」コースのレッスン 41/48。

C++の抽象基底クラスへの参照とC#のインターフェースへの参照は、どちらも置き換え可能な動作を実現します。この契約にC++の多重クラス継承は使用しません。ルーターは、特定の通知機能を自ら構築するのではなく、渡されたインターフェースオブジェクトを呼び出す必要があります。

インターフェースベースの関数は、同じ契約を実装する互いに無関係な実装を受け取れます。具象型に応じて切り替えるのではなく、インターフェースのメンバーを呼び出してください。この設計では、ルーターを変更せずに、呼び出し元がテスト用の実装や新しい通知機能を注入できます。このレッスンでは、サービスへの接続は行いません。

C++の参照

#include <algorithm>
#include <array>
#include <cctype>
#include <functional>
#include <iomanip>
#include <iostream>
#include <map>
#include <memory>
#include <optional>
#include <set>
#include <sstream>
#include <stdexcept>
#include <string>
#include <vector>
using namespace std;
struct Notifier { virtual string send(const string& message) const=0; virtual ~Notifier()=default; };
struct EmailNotifier: Notifier { string send(const string& message) const override { return "email:"+message; } };
int main() {
EmailNotifier concrete; Notifier& notifier=concrete; cout << notifier.send("ok") << "\n";
}

C#の宣言例

interface IMeasure { int Measure(string value); }
class TextLength : IMeasure { public int Measure(string value) { return value.Length; } }

Main内のC#の文

IMeasure measure = new TextLength();
Console.WriteLine(measure.Measure("word"));

これらは要点に絞った教材用の抜粋です。課題ファイルには実行可能な完全なラッパーが含まれており、上記のスニペットには関連する宣言と文が示されています。

参照出力:

email:ok

C#の出力:

4
challenge icon

チャレンジ

簡単

EmailNotifier.Send、SmsNotifier.Send、Router.Deliverを実装してください。channelはemailまたはsmsです。各通知クラスは、自身のチャンネル名とコロンを先頭に付けます。Routerは呼び出し元から渡された任意のINotifierに処理を委譲します。これらはテキスト形式を整えるモデルであり、実際のネットワークメッセージングではありません。

ロックされていないC#ファイルを編集してください。表示されているロック済みのMain.csは、説明された行を読み込み、Exercise.Solveを呼び出し、入力が変更されていないことを検証して、最後に改行を1つ付けて結果を出力します。宣言されているAPIを維持してください。2つ目のMainを追加したり、診断出力を表示したりしないでください。

ロックされたランチャーは、Solveのラッパーだけでなく、エクスポートされたヘルパーまたはクラスのAPIも個別に検証します。

自分で試してみよう

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 icon腕試し

このレッスンには短いクイズがあります。レッスンを始めて解答し、進捗を記録しましょう。

C++開発者のためのC#のすべてのレッスン

自分で練習してみよう: C#オンラインコンパイラ