LUA OOP 单例模式实现的 一个 方案
2016-05-01 00:03
513 查看
单例
存在这么一类class, 无论class怎么初始化, 产生的instance都是同一个对象。Code
string.toHTMLCode = function(self)
return encodeHTML(self)
end
-- Instantiates a class
local function _instantiate(class, ...)
-- 单例模式,如果实例已经生成,则直接返回
if rawget(class, "__singleton") then
-- _G[class]值为本class的实例
if _G[class] then
return _G[class]
end
end
local inst = setmetatable({__class=class}, {__index = class})
if inst.__init__ then
inst:__init__(...)
end
--单例模式,如果实例未生成,则将实例记录到类中
if rawget(class, "__singleton") then
if not _G[class] then
_G[class] = inst
end
end
return inst
end
-- LUA类构造函数
local function class(base)
local metatable = {
__call = _instantiate,
__index = base
}
-- __parent 属性缓存父类,便于子类索引父类方法
local _class = {__parent = base}
-- 在class对象中记录 metatable ,以便重载 metatable.__index
_class.__metatable = metatable
return setmetatable(_class, metatable)
end
---- code lua format ------
-- Instantiates a class local function _instantiate(class, ...) -- 抽象类不能实例化 if rawget(class, "__abstract") then error("asbtract class cannot be instantiated.") end -- 单例模式,如果实例已经生成,则直接返回 if rawget(class, "__singleton") then -- _G[class]值为本class的实例 if _G[class] then return _G[class] end end local inst = setmetatable({__class=class}, {__index = class}) if inst.__init__ then inst:__init__(...) end --单例模式,如果实例未生成,则将实例记录到类中 if rawget(class, "__singleton") then if not _G[class] then _G[class] = inst -- 对类对象增加实例获取接口 class.getInstance = function ( self ) return _G[class] end
-- 对类对象增加实例销毁 class.destroyInstance = function ( self ) return _G[class] end end end return inst end -- LUA类构造函数 local function class(base) local metatable = { __call = _instantiate, __index = base } -- __parent 属性缓存父类,便于子类索引父类方法 local _class = {__parent = base} -- 在class对象中记录 metatable ,以便重载 metatable.__index _class.__metatable = metatable return setmetatable(_class, metatable) end --- Test whether the given object is an instance of the given class. -- @param object Object instance -- @param class Class object to test against -- @return Boolean indicating whether the object is an instance -- @see class -- @see clone function instanceof(object, class) local meta = getmetatable(object) while meta and meta.__index do if meta.__index == class then return true end meta = getmetatable(meta.__index) end return false end
使用说明:
使用方法, class继承方式不变如果给定义的class设置一个 _singleton 为 true, 开启单利模式。
Dmenu = class() -- 菜单类 Dmenu.__singleton = true -- 开启单例模式
使用类创建实例:
local menu = Dmenu() if Dmenu:getInstance() == menu then print("true") end Dmenu:destroyInstance() menu:destroyInstance()
相关文章推荐
- LUA OOP编程实现方法
- 以一则LUA实例说明敏捷开发中“分离构造和使用”原则
- 对“tolua++导出C++子类后在Lua中无法添加新成员”这一问题的初步分析
- 150. Evaluate Reverse Polish Notation
- 自己实验lua
- lua面向对象封装及元表(metatable)性能测试
- 我理解的设计模式:单例模式
- LUA基本函数库
- Lua面向对象
- Lua模块处理
- Lua垃圾回收和弱引用
- Lua学习(六)元表和元方法
- Lua_第26章撰写 C 函数的技巧
- Ionic的项目结构(angluar js)
- Lua 5.2/5.3 热更新小结
- 记录lua的table转string一个问题
- 我理解的设计模式:工厂模式
- lua: pcall xpcall debug
- Lua_第25章 调用 C 函数
- C++与Lua5.3.2的相互调用