Valentine's Day is a float cloud-let's talk about the Lua Implementation of the singleton object.

Source: Internet
Author: User

I posted an article that is out of standard.Article, Claiming that the Lua singleton object can be implemented using the method described in this article.

It can be a reality, but it is too ugly, which does not reflect the beauty of Lua, but also comes with naming pollution. After reading FP, I came up with a more elegant implementation solution:

 

Hello ={}</P> <p> function Hello: New () -- Private method. <br/> local store = nil </P> <p> return function (Self) <br/> If store then return store end </P> <p> Print "create. "-- for test. <br/> Local o ={}< br/> setretriable (O, self) <br/> self. _ Index = self </P> <p> store = O <br/> return o <br/> end </P> <p> hello. instance = Hello: New () -- implement Single Instance Object. </P> <p> -- test following <br/> Local Hello = Hello: instance () --> create. <br/> Local hellohello = Hello: instance () -- no output </P> <p> local hi = Hello <br/> local hi = Hi: instance () -- the same with Hello: instance
Use closures to create more elegant implementations.

 

Oop implemented through meta-tables cannot implement encapsulation, so new is a private method that can only rely onProgramThe employee consciously ......

ASIDE: to implement encapsulated Oop, we can only implement it through closures. This is mentioned in Lua program design, but this method is not recommended by the author for unknown reasons. I guess it is probably because it cannot share the class method. Each object has all the data of the class and copies the method.

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.