Menu
CoddyTech

합성과 위임

Coddy의 C 개발자를 위한 Luau 코스 레슨. 48개 중 38번째.

C에서는 명시적인 수명을 가진 구조체 값을 내장하거나 협력 객체의 포인터를 저장할 수 있습니다. Luau는 테이블 참조를 저장하며, 참조 가능한 동안 해당 테이블은 유지됩니다. 공유 정책 변경이 아니라 독립성이 필요한 경우에만 상태를 복사하고, 제공된 협력 객체에 위임하세요.

C 비교

#include <stdio.h>
struct Policy {
    int factor;
    int (*apply)(const struct Policy *self, int quantity);
};
struct Order { const struct Policy *policy; };
static int multiply(const struct Policy *self, int quantity)
{
    return self->factor * quantity;
}
static int order_total(const struct Order *self, int quantity)
{
    return self->policy->apply(self->policy, quantity);
}
int main(void)
{
    struct Policy policy = {2, multiply};
    struct Order order = {&policy};
    printf("%d\n", order_total(&order, 3));
    return 0;
}

Luau 동작

합성은 협력 객체를 저장하고 공개 프로토콜을 통해 위임합니다. 구조적 타입으로 해당 프로토콜을 설명할 수 있지만, 관찰 가능한 위임이 여전히 계약입니다. 잠금된 드라이버는 대체 정책을 주입하므로 앱에서 하나의 정책을 하드 코딩하면 객체 API를 충족할 수 없습니다.

local policy={}
function policy:apply(n) return n*2 end
local order={policy=policy}
function order:total() return self.policy:apply(3) end
print(order:total())

예상 Luau 출력:

6
challenge icon

챌린지

쉬움

policy.luau에서 저장된 factor를 n에 곱하는 apply(n)을 사용해 가격 정책을 구현하세요. Model은 정책을 저장하고 total(n)을 제공합니다. 입력은 factor와 quantity입니다. 위임된 total을 반환하세요.

app.luau, model.luau, policy.luau를 편집하세요. 화면에 보이는 잠금된 main.luau는 stdin을 줄의 시퀀스로 읽고, app.run(lines)을 호출한 다음, 반환된 값을 마지막에 줄바꿈 하나를 붙여 출력합니다. 진단 메시지를 출력하거나 모듈 이름을 변경하지 마세요. 입력이 비어 있으면 빈 시퀀스가 됩니다. 모든 숫자 입력은 오버플로가 발생하지 않을 만큼 작습니다.

공개 API 검사: Policy.new(factor)는 apply(n)을 제공합니다. Model.new(policy)는 사용자 지정 apply 구현 객체를 포함해 전달된 정책에 total(n)을 위임하고, 해당 협력 객체를 독립적으로 유지해야 합니다. 잠금된 드라이버는 app.run을 호출하기 전에 이 동작을 검사합니다. 검사가 성공하면 아무것도 출력되지 않습니다.

직접 해보기

-- 공개 API 검사
do
local Model=require("./model")
local Policy=require("./policy")
local p=Policy.new(3)
assert(p:apply(4)==12 and p:apply(0)==0,"policy multiplies by its factor")
local a=Model.new(p)
assert(a:total(2)==6,"model must use its pricing policy")
local calls=0
local custom={apply=function(self,n) calls=calls+1;return n+7 end}
local b=Model.new(custom)
assert(b:total(5)==12 and calls==1,"model must delegate to the supplied collaborator")
assert(a:total(1)==3,"models retain their own policy")
end
local app = require("./app")
local lines = {}
for line in io.lines() do lines[#lines + 1] = line end
print(app.run(lines))
quiz icon실력 점검

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

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

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