Menu
CoddyTech

ממשקים והרכבה

שיעור 36 מתוך 48 בקורס C# למפתחי C++ של Coddy.

ב-C++ ממשקים מיוצגים לעיתים קרובות באמצעות מחלקת בסיס מופשטת, ומועברת הפניה שאורך החיים שלה חייב להיות ארוך מזה של המשתמש בה. ממשקים ב-C# הם חוזים מפורשים, ושיתופי פעולה הם הפניות מנוהלות. יש לשמר את ההאצלה תוך החלפת הנחות הבעלות ואורך החיים של C++ במודל האובייקטים של C#.

ממשק מגדיר חוזה של חבר נדרש, ומחלקות שמממשות אותו מצהירות על הקשר הזה. הרכבה שומרת משתף פעולה ומאצילה לו את העבודה. כך Checkout נשארת בלתי תלויה במחלקת הנחה מסוימת. מנהל ההתקן מזריק מדיניות משלו, ולכן קידוד קשיח של חישוב VIP בתוך Checkout לא יכול למלא את דרישות ה-API.

הפניה ל-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 PricePolicy { virtual int apply(int price) const=0; virtual ~PricePolicy()=default; };
struct StandardPolicy: PricePolicy { int apply(int price) const override { return price; } };
class Checkout { const PricePolicy& policy; public: explicit Checkout(const PricePolicy& p):policy(p) {} int total(int n) const { return policy.apply(n); } };
int main() {
StandardPolicy policy; Checkout checkout(policy); cout << checkout.total(40) << "\n";
}

הצהרות עזר ב-C#

interface IFormatter { string Format(string value); }
class Upper : IFormatter { public string Format(string value) { return value.ToUpperInvariant(); } }
class Display { private IFormatter formatter; public Display(IFormatter formatter) { this.formatter = formatter; } public string Render(string value) { return formatter.Format(value); } }

פקודות C# בתוך Main

Console.WriteLine(new Display(new Upper()).Render("pen"));

אלה קטעים ממוקדים להוראה. קובצי האתגר כוללים מעטפות מלאות שניתן להריץ; הקטעים שלמעלה מציגים את ההצהרות והפקודות הרלוונטיות.

פלט ההפניה:

40

פלט C#:

PEN
challenge icon

אתגר

קל

ממשו את StandardPolicy, את VipPolicy ואת Checkout בקבצים נפרדים. StandardPolicy מחזירה את המחיר; VipPolicy מחזירה 90 אחוז באמצעות חשבון של מספרים שלמים. המחירים הם מספרים אי־שליליים שהם כפולות של עשר. Checkout חייבת להעביר את הקריאה אל IPricePolicy שהוזרקה, כולל מדיניות מותאמת אישית שסופקה על ידי הקוראים.

ערכו את קובצי C# שאינם נעולים. הקובץ הנעול והגלוי Main.cs קורא את השורות המתוארות, קורא ל־Exercise.Solve, מוודא שהקלט לא השתנה ומדפיס את התוצאה עם תו שורה חדשה אחד בסוף. השאירו את ממשקי ה־API שהוגדרו. אל תוסיפו Main נוסף ואל תדפיסו פלט אבחון.

המשגר הנעול בודק בנפרד גם את ה־API של העזר או המחלקה שיוצאו, ולא רק את מעטפת Solve.

נסו בעצמכם

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 = I(input[0]); string before0=Snapshot(a0);
var a1 = input[1] == "true"; string before1=Snapshot(a1);
if (new StandardPolicy().Apply(40) != 40 || new VipPolicy().Apply(100) != 90 || new Checkout(new ProbePolicy()).Total(10) != 17) throw new Exception("Policy 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 ProbePolicy : IPricePolicy { public int Apply(int price) { return price+7; } }
quiz iconבחנו את עצמכם

השיעור הזה כולל חידון קצר. התחילו את השיעור כדי לענות עליו ולעקוב אחרי ההתקדמות.

כל השיעורים ביחידה C# למפתחי C++

תרגלו בעצמכם: קומפיילר C# אונליין