Menu
CoddyTech

コンポジションと委譲

Coddyの「C開発者のためのLuau」コースのレッスン 38/48。

Cでは、コンポジションによって構造体の値を埋め込んだり、明示的な有効期間を持つ協力オブジェクトへのポインターを格納したりできます。Luauではテーブルへの参照が格納され、到達可能な間は保持されます。共有ポリシーの変更ではなく独立性がAPIで必要とされる場合に限り、提供された協力オブジェクトを介して委譲し、その状態をコピーします。

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での動作

コンポジションでは協力オブジェクトを格納し、その公開プロトコルを介して処理を委譲します。構造的型でそのプロトコルを記述できますが、実際に観察できる委譲こそが契約です。ロックされたドライバーは別のポリシーを注入するため、アプリ内で1つのポリシーをハードコードしてもオブジェクト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 に価格設定ポリシーを実装し、apply(n) で n に保存された係数を掛けます。Model はポリシーを保持し、total(n) を提供します。入力は係数と数量です。委譲された合計を返します。

app.luau、model.luau、policy.luau を編集します。表示されているロック済みの main.luau は、標準入力を行の並びとして読み込み、app.run(lines) を呼び出し、戻り値を末尾に改行を1つ付けて出力します。診断メッセージを出力したり、モジュール名を変更したりしないでください。入力が空の場合は、空の並びになります。すべての数値入力はオーバーフローしない範囲の小さな値です。

公開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オンラインコンパイラ