策略模式Lua实现


策略模式Lua实现

Strategy = {}

ConcreteStrategyA = {}

ConcreteStrategyB = {}

ConcreteStrategyC = {}

Context = {strategy = nil}

function Strategy:new(o)
 o = o or {}
 setmetatable(o,self)
 self.__index = self
 return o;
end

function Strategy:AlgorithmInterface()
 print("逻辑接口")
end

ConcreteStrategyA = Strategy:new()

function ConcreteStrategyA:AlgorithmInterface()
 print("具体策略A")
end

function 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()
end

context = Context:new({},ConcreteStrategyA:new())
context:ContextInterface()

上面的代码的输出结果是:具体的策略A

如果你把

function ConcreteStrategyA:AlgorithmInterface()

注释掉,输出的结果应该就会是:逻辑接口。

有兴趣的同学也可以将ConcreteStrategyB,ConcreteStrategyC加上去,练练手。

交流群:315249378

Lua 的详细介绍:请点这里
Lua 的下载地址:请点这里

推荐阅读:

Lua 语言 15 分钟快速入门

Lua程序设计(第2版)中文 PDF

Lua程序设计(第二版)阅读笔记

NetBSD 将支持用 Lua 脚本开发内核组件

相关内容