2

Sweet Snippet 之 成对接口调用

 7 months ago
source link: https://blog.csdn.net/tkokof1/article/details/135767709
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Sweet Snippet 之 成对接口调用

tkokof1 于 2024-01-23 11:38:22 发布

本文简述了成对接口存在一些调用问题

一般的程序开发中,总是会涉及很多的状态控制(开关),往往涉及到成对接口的调用,抽象来说,我们会有类似下面的代码实现:

local program_state = { enabled = false }

function program_state:enable()
    self.enabled = true
end

function program_state:disable()
    self.enabled = false
end

function program_state:is_enabled()
    return self.enabled
end

return program_state

代码是比较简单明了的,但是从实际使用角度来说又是不够方便的,因为实际的程序逻辑中可能会存在嵌套调用:

enable(from logic a) -> enable(from logic b) -> disable(from logic a) -> disable(from logic b)

按照目前 enable/disable 的实现,上述这种嵌套调用会导致程序状态被提前 disable, 继而造成不正确的程序表现.

实现上我们可以采用数值累加(及递减)的方式来设置程序状态:

local program_state = { enabled = 0 }

function program_state:enable()
    self.enabled = self.enabled + 1
end

function program_state:disable()
    self.enabled = self.enabled - 1
end

function program_state:is_enabled()
    return self.enabled > 0
end

return program_state

上述实现能够很好的解决 嵌套调用 的问题,但是无法解决 Unbalanced 调用问题(即 enable/disable 调用不匹配):

enable(from logic a) -> enable(from logic a) -> disable(from logic a)

上述调用会导致程序状态一直维持 enable 状态,继而造成不正确的程序表现,不过准确来说,上述问题其实是源于调用方,调用方应该自行维护状态来确保不出现 Unbalanced 调用,但是我们仍然可以继续扩展接口层来支持 Unbalanced 调用.

  • map 方式

我们可以给接口添加 reason 参数来分辨不同的调用逻辑,同时内部使用 map 来进行状态管理:

local program_state = { enable_reasons = {} }

function program_state:enable(reason)
    reason = reason or 0
    self.enable_reasons[reason] = true
end

function program_state:disable(reason)
    reason = reason or 0
    self.enable_reasons[reason] = nil
end

function program_state:is_enabled()
    return next(self.enable_reasons) ~= nil
end

return program_state
newCodeMoreWhite.png

map方式实现可以同时解决 嵌套调用 和 Unbalanced 调用问题,但是代价有些高(需要维护 map 结构),其实对于特定的程序来说,对于某一程序状态的 reason 调用往往是有限的,基于此,我们可以改用 bit 形式来进行状态管理:

  • bit 方式
local program_state = { enable_reasons = 0 }

function program_state:enable(reason)
    reason = reason or 0
    self.enable_reasons = self.enable_reasons | (1 << reason)
end

function program_state:disable(reason)
    reason = reason or 0
    self.enable_reasons = self.enable_reasons & (~(1 << reason))
end

function program_state:is_enabled()
    return self.enable_reasons ~= 0
end

return program_state
newCodeMoreWhite.png

上述 bit 方式对于一般的程序基本都是适用的,同时也解决了 嵌套调用 和 Unbalanced 调用问题,实际开发中可以参考使用.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK