Singleton: Difference between revisions
Content added Content deleted
Line 1,646: | Line 1,646: | ||
method instance { $instance; } |
method instance { $instance; } |
||
}</lang> |
}</lang> |
||
=={{header|Phix}}== |
|||
Not really any special handling for singletons in Phix, but you can do something like this, |
|||
or keep check() private and invoke it internally from a few critical routines. |
|||
Needs 0.8.1+ |
|||
<lang Phix>-- <separate include file> |
|||
object chk = NULL |
|||
class singleton |
|||
public procedure check() |
|||
if chk==NULL then |
|||
chk = this |
|||
elsif this!=chk then |
|||
?9/0 |
|||
end if |
|||
?"ok" |
|||
end procedure |
|||
end class |
|||
global singleton s = new() |
|||
--global singleton s2 = new() |
|||
-- </separate include file> |
|||
s.check() |
|||
--s2.check() -- dies</lang> |
|||
While all classes are technically global in the sense that builtins\structs.e knows all about them, the |
|||
implicit associated user defined type is by default private (ie w/o "global" in front of the class def). |
|||
The above separate file prohibits the use of (other) <code>singleton s = new()</code> everywhere, however |
|||
<code>class s = new("singleton")</code> could still be used anywhere, and that way get duplicates. |
|||
One obvious alternative (of no special merit imo) might be to replace that global singleton s with: |
|||
<lang Phix>global function get_singleton() |
|||
if chk==NULL then |
|||
chk = new("singleton") |
|||
end if |
|||
return chk |
|||
end function</lang> |
|||
Technically, builtins/struct.e looks like it could easily be modified to support something very similar |
|||
to the Python Borg pattern, by appropriately sharing cdx/tid in new(). However it would be even better |
|||
to share the whole delete_routine()'d res, and that would probably be best achieved by setting a new |
|||
flag, say S_SINGLETON or S_STATIC, alongside and triggered via similar syntax to S_ABSTRACT/S_NULLABLE. |
|||
Maybe. |
|||
=={{header|PHP}}== |
=={{header|PHP}}== |