Singleton pattern

This is an old revision of Singleton pattern, edited by Thaddy at . The current revision is 150505.

{
  Implements singleton pattern by using FreePascal's property feature.
  
  A global block can declare properties, just as they could be defined 
  in a class. The difference is that the global property does not need 
  a class instance: there is only one instance of this property. 

  In this case the actual singleton is hidden behind a local writeable
  const. This actually stored in global space, but only accessible from 
  within its local constant. Since the property has only read access it
  makes that it can only be accessed read-only: a singleton.

  You must make sure the underlying class is free'd.
  That is no problem, because you can call free on the property.
}

{$mode objfpc}{$H+}
uses 
  classes;
  
  // this can be moved to a separate unit
  function InvokeList:TStringlist;inline;
  {$push}{$J+}const value:TStringlist = nil;{$pop}
  begin
    if value = nil then value := TStringlist.create;
    Result := Value;
  end;

  property List:TStringlist read InvokeList;

begin
  List.Add('text added');
  Writeln(List.Text);
  readln;
  List.free;
end.