Saturday, 15 February 2014

design patterns - Singleton in go -


How does one implement a singleton design pattern in a programming language? Whether or not to apply a singleton pattern, isolation of this argument is a good idea, here is a possible implementation:

  Package Singleton Type Single Structure {O Interface {}; } Var instantiated * single = zero func new () * single {instantiated == blue {instantiated = new (single); } Return immediately; }  

single and instant are private, but new () is public, thus you < Without code> single can not instantiate directly through New () , and it tracks the number of instant with the private boolean instantiated . Adjust to adjust the taste of single .

However, as many others, this thread is not secure, unless you are just starting your code in init) . A better way would be to take advantage of sync.Once to work hard for you:

  Package Singleton Import "Sync" Type Single Structure {O Interface { }; } Var instantiated * single var once sync.Once func new () * single {one.Do (func () {instantiated = & single {}} instantiated}  

Also see Hassan Jay's suggestion to think of a package, like as a singleton and finally, what others are suggesting: these singletons are often indicators of problematic implementation. .


No comments:

Post a Comment