Menu
CoddyTech

인터페이스와 합성

Coddy의 R 개발자를 위한 C# 코스 레슨. 48개 중 36번째.

R S3에서는 클래스에 apply_policy.standard_policy와 같은 메서드가 존재하는 한 정책이 checkout_total()과 함께 작동하며, 메서드가 없으면 제네릭이 호출될 때만 오류가 발생합니다. C#의 인터페이스 호환성은 명목적입니다. 클래스가 IPricePolicy를 선언하고 컴파일러가 Apply를 구현했는지 확인합니다. 합성과 의존성 주입은 여전히 체크아웃 로직을 구체적인 정책과 분리합니다.

인터페이스는 필수 멤버 계약의 이름을 지정하고, 이를 구현하는 클래스는 그 관계를 선언합니다. 합성은 협력 객체를 저장하고 작업을 그 객체에 위임합니다. 이렇게 하면 Checkout을 특정 할인 클래스와 독립적으로 유지할 수 있습니다. 드라이버는 자체 정책을 주입하므로, Checkout에 VIP 산술 연산을 하드 코딩하는 방식으로는 API를 충족할 수 없습니다.

R 참조

apply_policy <- function(policy, price) UseMethod("apply_policy")
apply_policy.standard_policy <- function(policy, price) price
new_checkout <- function(policy) list(policy = policy)
checkout_total <- function(checkout, price) apply_policy(checkout$policy, price)
standard <- structure(list(), class = "standard_policy")
cat(checkout_total(new_checkout(standard), 40), "\n", sep = "")

C# 지원 선언

interface IPricePolicy { int Apply(int price); }
class StandardPolicy : IPricePolicy { public int Apply(int p) { return p; } }
class Checkout { private IPricePolicy policy; public Checkout(IPricePolicy p) { policy=p; } public int Total(int n) { return policy.Apply(n); } }

Main 내부의 C# 문장

IPricePolicy policy = new StandardPolicy();
Console.WriteLine(new Checkout(policy).Total(40));

이는 핵심 내용에 초점을 맞춘 학습용 발췌문입니다. 과제 파일에는 실행 가능한 완전한 래퍼가 포함되어 있으며, 위 코드 조각은 관련 선언과 문장을 보여 줍니다.

참조 출력:

40

C# 출력:

40
challenge icon

챌린지

쉬움

각각의 파일에 StandardPolicy, VipPolicy, Checkout을 구현하세요. Standard는 가격을 반환하고, 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; } }
quiz icon실력 점검

이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.

R 개발자를 위한 C#의 모든 레슨

직접 연습해 보세요: 온라인 C# 컴파일러