Menu
CoddyTech

委托给协作对象

Coddy 面向 C 开发者的 Lua 课程的第 38 课,共 48 课。

组合让订单可以请求独立的定价策略来计算总价。C 设计可以存储指向策略的指针,以及描述其操作的函数指针。Lua 存储对协作对象表的引用,并调用它的方法。订单不必重复定价公式,只需保留协作对象并传递数量。这些示例使用系数 2,但其他策略也可以用不同规则实现相同的操作。

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;
}

Lua

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

移植陷阱

存储协作对象并不会复制它。C 必须确保被指向的策略在每次使用时都保持有效;Lua 会自动让被引用的表保持可访问。在这两个示例中,修改共享策略的状态都会影响使用该策略的所有订单。

challenge icon

挑战

简单

在 policy.lua 中实现定价策略,使用 apply(n) 将 n 乘以存储的因子。Model 保存该策略并提供 total(n)。输入包括因子和数量。返回委托计算得到的总数。

编辑 app.lua、model.lua 和 policy.lua。可见的锁定文件 main.lua 会将 stdin 读入一个行序列,调用 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))
quiz icon自我测试

这节课包含一个小测验。开始学习即可作答,并记录你的进度。

面向 C 开发者的 Lua中的所有课

自己练习: Lua 在线编译器