Here's how it could be done (Warning, I have not tested it):
Code: Select all
local Singleton = { static = {} }
function Singleton:included(theClass)
theClass.static._instance = theClass:new()
-- override new to throw an error
theClass.static.new = function() error("Use " .. theClass.name .. ":getInstance() instead of :new()") end
end
function Singleton.static:getInstance()
return self._instance
end
return Singleton
You can find more documentation about included here:
https://github.com/kikito/middleclass/w ... s#included
Now I should retire to my cave, but I honestly feel I would be failing if I didn't give you some words of caution. Please feel free to ignore them.
A singleton, even if wrapped inside a class and a mixin, is just a global variable. Using this mixin is equivalent to doing a global variable like this:
With a different syntax.
If you really want to go the Singleton route, I would recommend considering using globals instead; it's more honest and it'll give you visibility about what is "really being shared globally". Singletons will give you a false sense of security that will push you to share more than it's really necessary.
If you are trying to use Singletons because you are trying to avoid global variables, consider passing whatever you need as a parameter to the constructor of whatever needs it (that's an OOP principle, pass dependencies on the constructor).