Oxygene by Example – Singleton

December 16, 2011 in Uncategorized

This is the first item in my series “Oxygene by Example”, this time about singletons.

Singleton classes are used when there’s only ever one instance of a class needed. They differ from Static Classes in that they have an actual instance, can implement an interface and you can use them as parameters to a method. There are different ways of writing singletons, but the easiest way is by using a readonly class variable:

  IObjectCache = interface
    method GetOrCreate(aName: string; aNeedNewValue: Func): T;
  GlobalObjectCache = class(IObjectCache)
    fCache: Dictionary := new Dictionary;
    constructor; empty; // required to be private; so nobody can instantiate it
    class property Instance: MySingleton := new MyObjectCache; readonly;
    method GetOrCreate(aName: string; aNeedNewValue: Func): T;
method GlobalObjectCache.GetOrCreate(aName: string; aNeedNewValue: Func): T;
  locking fCache do begin
    var lValue: Object;
    if fCache.TryGetValue(aName, out lValue) then exit T(lValue);
    result := aNeedNewValue();
    fCache.Add(aName, result);

Using the singleton is simple, GlobalObjectCache.Instance gives access to all instance members of the class:

  lblSystemName.Text := GlobalObjectCache.Instance.GetOrCreate(
    'ComputerName', -> Environment.MachineName);

The latest version of this article can be found Here.

Comments are closed.