Singleton: Difference between revisions

Content added Content deleted
Line 1,336: Line 1,336:
=={{header|Racket}}==
=={{header|Racket}}==


Singletons are not very useful in Racket, because functions that use module state are more straightforward. However, it is possible to construct one by simply not exporting the class value that constructs the singleton:
Singletons are not very useful in Racket, because functions that use module state are more straightforward. However, classes are first class values, and therefore they follow the same rules as all other bindings. For example, a class can be made and instantiated but not provided to client files:
<lang racket>

<lang lisp>
#lang racket
#lang racket

(provide instance)
(provide instance)

(define singleton%
(define singleton%
(class object%
(class object%
(super-new)))
(super-new)))
(define instance (new singleton%))
</lang>


Or better, not name the class at all:
(define instance (new singleton%))
<lang racket>
#lang racket
(provide instance)
(define instance
(new (class object%
(define/public (foo) 123)
(super-new))))
</lang>
</lang>