A scenario for the implementation of the LUA OOP singleton pattern

Source: Internet
Author: User

Single case

There is such a class, no matter how the class is initialized, the resulting instance are the same object.

Code

String.tohtmlcode = function (self)

return encodehtml (self)

End

--Instantiates a class

Local function _instantiate (class, ...)

--Singleton mode, if the instance is already generated, return directly

If Rawget (class, "__singleton") Then

--_g[class] value is an instance of this class

If _g[class] Then

return _g[class]

End

End

Local Inst = setmetatable ({__class=class}, {__index = class})

If Inst.__init__ Then

Inst:__init__ (...)

End

--Singleton mode, if the instance is not generated, logs the instance to a class

If Rawget (class, "__singleton") Then

If not _g[class] Then

_g[class] = Inst

End

End

Return Inst

End

--LUA class constructors

Local function class (base)

Local metatable = {

__call = _instantiate,

__index = Base

}

--__parent Property Cache parent class for child class Index parent class method

Local _class = {__parent = base}

--Record metatable in the class object to overload Metatable.__index

_class.__metatable = metatable

Return setmetatable (_class, metatable)

End

Description

Using the method, class inherits the same way

If you set a _singleton to true for the defined class, turn on simple interest mode.

A scenario for the implementation of the LUA OOP singleton pattern

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.