Version française
Home     About     Download     Resources     Contact us    
Browse thread
The "Objective" part of Objective Caml
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: -- (:)
From: Matt Gushee <matt@g...>
Subject: Re: Ant: [Caml-list] The "Objective" part of Objective Caml
Brian Hurt wrote:

>> Don't you have immediate objects [1] to do singletons ?
> 
> 
> No- because immediate objects still allocate a new object every time
> they are evaluated.  I suppose you could do:
> 
> let factory =
>     let myobject = new myclass in
>     fun () -> myobject
> ;;
> 
> and do a factory method, but there is no way (that I know of) to prevent
> someone else from doing:
>     let myotherobject = new myclass
> and allocating a different object of the same class.

Just for amusement, here are two ways:

[1]

   let factory =
     let instance_exists = ref false in
     let mkobj () =
       object
         initializer
           if !instance_exists then failwith "Sorry."
           else instance_exists := true
         ...
       end in
     mkobj

[2]

  foo.mli:
  --------

  class type t_myclass =
    object
      ....
    end

  val factory : unit -> t_myclass

  foo.ml:
  -------

  class type t_myclass =
    object
      ....
    end

  class myclass =
    object
      ....
    end

  let instance : t_myclass option ref = ref None

  let factory () =
    match !instance with
    | Some i -> i
    | None -> let i = new myclass in instance := Some i; i


> No, the proper way to do singletons in Ocaml is with modules, not objects.

But Brian is right, I'm sure.

-- 
Matt Gushee
Englewood, CO, USA