I have little knowledge about design pattern, today I learnt the Singleton design pattern, so I tried to implement it in Scheme like this
(define nil '())
(define Singleton
(let ((instance nil))
(lambda ()
(if (null? instance)
(let ((a 0))
(define (dispatch msg)
(cond ((eq? msg 'get)
(lambda () a))
((eq? msg 'set)
(lambda (v)
(begin (set! a v)
'ok)))))
(set! instance dispatch)))
instance)))
(define a (Singleton))
(define b (Singleton))
(eq? a b);;#t
((a 'set) 3)
((b 'get));;3
is my understand and implementation to this design pattern right?
Your implementation is correct, because (eq? a b)
is #t
.
I would simplify it a little bit (although this is not Code Review) like so:
nil
, '()
will do(a 'set 3)
rather than ((a 'set) 3)
case
instead of cond
so
(define Singleton
(let ((a 0)) ; instance variables
(define (get) a)
(define (set v) (set! a v) 'ok)
(define (dispatch msg . args) ; dispatcher procedure
(case msg
((get) (apply get args))
((set) (apply set args))
(else (error "unknown message"))))
(lambda () dispatch))) ; return dispatch procedure
then
(define a (Singleton))
(define b (Singleton))
(eq? a b) ;; #t
(a 'set 3) ;; 'ok
(b 'get) ;; 3
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments