인터페이스와 구성
Coddy의 C 개발자를 위한 C# 코스 레슨. 48개 중 36번째.
C에는 인터페이스가 없으므로 C 개발자는 이를 함수 포인터로 이루어진 구조체로 모델링하고 그에 대한 포인터를 저장합니다. 각 구현이 테이블을 채우고 해당 정책을 사용하는 코드가 끝날 때까지 정책이 살아 있도록 하는 것은 개발자의 몫입니다. C# 인터페이스는 컴파일러가 검사하는 계약입니다. 인터페이스를 선언한 클래스는 모든 멤버를 구현해야 하며, 저장된 협력 객체는 Display가 참조하는 동안 살아 있는 관리 참조입니다. 위임 방식은 동일하지만, 수동으로 테이블을 관리하고 수명을 추적할 필요가 없습니다.
인터페이스는 필수 멤버 계약을 명시하고, 구현 클래스는 그 관계를 선언합니다. 컴포지션은 협력 객체를 저장하고 작업을 그 객체에 위임합니다. 이렇게 하면 Checkout이 특정 할인 클래스에 종속되지 않습니다. 드라이버가 자체 정책을 주입하므로 Checkout에 VIP 계산을 하드코딩하는 것으로는 API를 충족할 수 없습니다.
C 참조
#include <stdio.h>
struct PricePolicy {
int (*apply)(const struct PricePolicy *self, int price);
};
static int standard_apply(const struct PricePolicy *self, int price) {
(void)self;
return price;
}
struct Checkout { const struct PricePolicy *policy; };
static int checkout_total(const struct Checkout *c, int n) {
return c->policy->apply(c->policy, n);
}
int main(void) {
struct PricePolicy standard = { standard_apply };
struct Checkout checkout = { &standard }; /* standard는 checkout보다 오래 유지되어야 합니다 */
printf("%d\n", checkout_total(&checkout, 40));
return 0;
}
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); } }Main 내부의 C# 문장
Console.WriteLine(new Display(new Upper()).Render("pen"));이 예제들은 핵심 내용만 다루는 교육용 발췌문입니다. 과제 파일에는 실행 가능한 전체 래퍼가 포함되어 있으며, 위 코드 조각에는 관련 선언과 문장만 나와 있습니다.
참조 출력:
40C# 출력:
PEN챌린지
쉬움StandardPolicy, VipPolicy, Checkout을 각각 별도의 파일에 구현하세요. StandardPolicy는 가격을 반환하고, VIP는 정수 연산을 사용해 가격의 90퍼센트를 반환합니다. 가격은 음수가 아니며 10의 배수입니다. Checkout은 호출자가 제공하는 사용자 지정 정책을 포함해 주입된 IPricePolicy에 위임해야 합니다.
잠금 해제된 C# 파일을 수정하세요. 화면에 표시되는 잠긴 Main.cs는 설명된 줄을 읽고, Exercise.Solve를 호출하며, 입력이 변경되지 않았는지 확인하고, 마지막에 개행 문자를 하나 붙여 결과를 출력합니다. 선언된 API를 유지하세요. 두 번째 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 = 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; } }
이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.
C 개발자를 위한 C#의 모든 레슨
1여기서 시작하기
첫 C# 프로그램 실행하기직접 연습해 보세요: 온라인 C# 컴파일러