Singleton: Difference between revisions
Content added Content deleted
Mercerenies (talk | contribs) (Latitude language added) |
(Added Wren) |
||
Line 2,091: | Line 2,091: | ||
} |
} |
||
}</lang> |
}</lang> |
||
=={{header|Wren}}== |
|||
Although it's possible to create a singleton in Wren, you have to rely on no one calling the 'private' constructor directly. This is because there is currently no way to create a private method in Wren - all you can do is to suffix the name with an underscore to indicate by convention it's for internal use only. |
|||
In practice, it's unlikely anyone would bother; they'd just create a class with static methods and/or fields only which is effectively a singleton as there's only ever a single instance of a static field. |
|||
<lang ecmascript>class Singleton { |
|||
// Returns the singleton. If it hasn't been created, creates it first. |
|||
static instance { __instance == null ? __instance = Singleton.new_() : __instance } |
|||
// Private constructor. |
|||
construct new_() {} |
|||
// instance method |
|||
speak() { System.print("I'm a singleton.") } |
|||
} |
|||
var s1 = Singleton.instance |
|||
var s2 = Singleton.instance |
|||
System.print("s1 and s2 are same object = %(Object.same(s1, s2))") |
|||
s1.speak() // call instance method</lang> |
|||
{{out}} |
|||
<pre> |
|||
s1 and s2 are same object = true |
|||
I'm a singleton. |
|||
</pre> |
|||
=={{header|zkl}}== |
=={{header|zkl}}== |