[plt-scheme] Singleton pattern using class.ss

From: Noel Welsh (noelwelsh at gmail.com)
Date: Wed Dec 12 11:57:17 EST 2007

On Dec 12, 2007 2:33 PM, Stephen De Gabrielle <stephen at degabrielle.name> wrote:
...
> I'm trying to work out the class.ss equivalent of java class methods and
> fields like this;
>
> > public class ActivityManager extends Thread {
> > [...]
> >    private synchronized static ActivityManager getInstance() {
> >        if ( s_instance == null || !s_instance.isAlive() ) {
> >            s_instance = new ActivityManager();
> >        }
> >        return s_instance;
> >    }

A direct translation would use a semaphore to provide the locking, and
s_instance would be #f or an activity-manager.

However, this is dangerous.  There are more and different abstractions
available in Scheme than in Java.  It is better to write idiomatic
Scheme than translate Java directly.

Here's a more idiomatic but still messy translation:

(define (make-instance)
  'foo)

(define instance-channel (make-channel))

(define instance-manager
  (thread
   (lambda ()
     (let loop ([instance #f])
       (channel-get instance-channel)
       (if instance
           (begin
             (channel-put instance-channel instance)
             (loop instance))
           (begin
             (let ([instance (make-instance)])
               (channel-put instance-channel instance)
               (loop instance))))))))


(define (get-instance)
  (channel-put instance-channel 'gimme-it)
  (channel-get instance-channel))

>  [code from prefuse.org; I'm porting bits to scheme]

[Pleased to see it's named after Prefuse 73!]

> The 'Factory Pattern' is next for me. Any suggestions gratefully accepted.

Wouldn't a function suffice in this case?

N.


Posted on the users mailing list.