组合与委托
Coddy 面向 C# 开发者的 Luau 课程的第 38 课,共 48 课。
C# 组合可以保留一个类协作者,也可以复制一个结构体,而其中的引用字段仍可能是共享的。Luau 表字段会保留引用。通过提供的策略进行委托,并明确判断契约要求的是共享行为还是独立状态副本。
C# 对比
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
var order=new Order(new DoublePolicy()); Console.WriteLine(order.Total());
interface IPolicy {int Apply(int n);}
class DoublePolicy:IPolicy {public int Apply(int n)=>n*2;}
class Order {private IPolicy policy; public Order(IPolicy p){policy=p;} public int Total()=>policy.Apply(3);}
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挑战
简单在 policy.luau 中实现定价策略,使用 apply(n) 将 n 乘以存储的因子。Model 存储该策略,并提供 total(n)。输入为因子和数量。返回委托计算得到的总数。
编辑 app.luau、model.luau 和 policy.luau。可见的锁定文件 main.luau 会将标准输入读入一个行序列,调用 app.run(lines),并打印其返回值,末尾带一个换行符。不要打印诊断信息,也不要更改模块名称。空输入会得到空序列。所有数值输入都足够小,不会溢出。
公共 API 检查:Policy.new(factor) 提供 apply(n)。Model.new(policy) 必须将 total(n) 委托给提供的策略,包括实现了 apply 的自定义对象,并独立保留该协作者。锁定的驱动程序会在调用 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))
这节课包含一个小测验。开始学习即可作答,并记录你的进度。
面向 C# 开发者的 Luau中的所有课
自己练习: Luau 在线编译器