策略模式Lua实现
[日期:2013-11-11] |
来源:Linux社区
作者:yitouhan |
[字体:大 中 小]
|
策略模式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
|