歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> 策略模式Lua實現

策略模式Lua實現

日期:2017/3/1 9:51:28   编辑:Linux編程

策略模式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 的下載地址:請點這裡

Copyright © Linux教程網 All Rights Reserved