基于协议的多态
Coddy 面向 C# 开发者的 Lua 课程的第 40 课,共 48 课。
C# 接口要求显式实现,而 Lua 表可以通过提供使用方所需的可调用方法来参与。每个方法都必须统一是否传入 self。分别测试每个模块,并根据可观察到的行为判断,而不是依赖具体类型名称。匹配的源接口不会成为运行时 Lua 声明。
C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
IChannel[] channels={new Email(),new Sms()}; Console.WriteLine(string.Join("|",channels.Select(c=>c.Send("hi"))));
interface IChannel {string Send(string text);}
class Email:IChannel {public string Send(string text)=>"email:"+text;}
class Sms:IChannel {public string Send(string text)=>"sms:"+text;}
Lua 5.1
local email={send=function(self,text) return "email:"..text end}
local sms={send=function(self,text) return "sms:"..text end}
local out={}
for _,c in ipairs({email,sms}) do out[#out+1]=c:send("hi") end
print(table.concat(out,"|"))移植规则
在每个 Lua 通道上提供所需的可调用方法。
挑战
简单输入是一行消息。实现 email.lua 和 sms.lua,让它们各自返回一个包含 send(self,text) 的表。给 text 加上 email: 或 sms: 前缀。app 会调用这两个模块,并用竖线连接返回的输出。空消息也是有效的。
编辑 app.lua、email.lua 和 sms.lua。可见但已锁定的 main.lua 会将 stdin 读入一个行序列,调用 app.run(lines),并在末尾添加一个换行符来打印返回值。不要打印诊断信息,也不要更改模块名称。空输入会得到一个空序列。所有数字输入都足够小,不会溢出。
公开 API 检查:两个通道模块都必须独立实现 send(self, text),包括处理空文本。锁定的驱动程序会在调用 app.run 之前检查此行为。检查成功时不会打印任何内容。
亲手试试
-- 公共 API 检查
do
local email,sms=require("email"),require("sms")
assert(email:send("hi")=="email:hi" and sms:send("hi")=="sms:hi","both channels implement send")
assert(email:send("")=="email:" and sms:send("")=="sms:","send preserves empty messages")
end
local app = require("app")
local lines = {}
for line in io.lines() do lines[#lines + 1] = line end
print(app.run(lines))
这节课包含一个小测验。开始学习即可作答,并记录你的进度。
面向 C# 开发者的 Lua中的所有课
自己练习: Lua 在线编译器