[Prev][Next][Index][Thread]

Re: simple method dispatch question



"Michael T. Richter" <mtr@ottawa.com> writes:

> Jason, you just solved a minor question I've had ever since I
> started to experiment with Dylan: What use are singletons?

Not much really since singletons are practically supported by the
language. But here's an example of a 'singleton' class as per the GOF
book as presented by Andy Armstrong a while ago:

------------------8<---------------
  // An implementation of the singleton pattern - based on example
  // posted to comp.lang.dylan by Andy Armstrong.

  define constant *singleton-instances* = make(<table>);

  define open abstract class <singleton-class> (<object>)
  //  each-subclass slot
  //    singleton-instance :: false-or(subclass(<singleton-class>)) = #f;
  end class <singleton-class>;

  define method make ( class :: subclass(<singleton-class>), #key )
   => (object :: <singleton-class>)
    element(*singleton-instances*, class, default: #f) 
      | begin
          *singleton-instances*[class] := next-method()
        end
  end method make;
------------------8<---------------

Note that 'each-subclass' wasn't used as you need an instance of a
class to modify the class slot - and you don't have one initally with
a singleton. 

Example use:

  define class <my-class> (<singleton-class>)
  end;

  begin
    let a = make(<my-class>);
    let b = make(<my-class>);
    a == b
  end; // should be #t


Chris.
-- 
http://www.double.co.nz/dylan




Follow-Ups: References: