策略模式Lua实现

2014-11-24 02:31:58 · 作者: · 浏览: 6

策略模式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


推荐阅读