Welcome 微信登录
编程资源 图片资源库 蚂蚁家优选 PDF转换器

首页 / 操作系统 / Linux / 策略模式Lua实现

策略模式Lua实现Strategy = {}ConcreteStrategyA = {}ConcreteStrategyB = {}ConcreteStrategyC = {}Context = {strategy = nil}function Strategy:new(o)
 o = o or {}
 setmetatable(o,self)
 self.__index = self
 return o;
endfunction Strategy:AlgorithmInterface()
 print("逻辑接口")
endConcreteStrategyA = Strategy:new()function ConcreteStrategyA:AlgorithmInterface()
 print("具体策略A")
endfunction Context:new(o,s)
 o = o or {}
 setmetatable(o,self)
 self.__index = self
 if s ~= nil then
  o.strategy = s
 end
 return o;
end
function Context:ContextInterface()
 self.strategy:AlgorithmInterface()
endcontext = Context:new({},ConcreteStrategyA:new())
context:ContextInterface()上面的代码的输出结果是:具体的策略A如果你把function ConcreteStrategyA:AlgorithmInterface()注释掉,输出的结果应该就会是:逻辑接口。有兴趣的同学也可以将ConcreteStrategyB,ConcreteStrategyC加上去,练练手。交流群:315249378Lua 的详细介绍:请点这里
Lua 的下载地址:请点这里推荐阅读:Lua 语言 15 分钟快速入门 http://www.linuxidc.com/Linux/2013-06/86582.htmLua程序设计(第2版)中文 PDF http://www.linuxidc.com/Linux/2013-03/81833.htmLua程序设计(第二版)阅读笔记 http://www.linuxidc.com/Linux/2013-03/81834.htmNetBSD 将支持用 Lua 脚本开发内核组件 http://www.linuxidc.com/Linux/2013-02/79527.htm