Results 1 to 1 of 1

Thread: Een singleton class implementeren

  1. #1

    Een singleton class implementeren

    Omschrijving

    Een singleton class is een class waarvan maar één instantie kan zijn. In het ideale geval houdt een class zelf een teller (reference counter) bij in een class property om te controleren of er een nieuwe instantie gemaakt mag/moet worden. Helaas ondersteunt Delphi geen class properties of class fields om deze waarde in vast te houden. Daarom wordt vaak een globale variable gebruikt hetgeen vanuit OO standpunt niet zo mooi is.
    Een mooiere oplossing is het gebruik van Assignable Consts in een class functie.

    Code

    Code:
    type
      TGTSingleton = class(TObject)
      private
        class function RefCount: PInteger;
      public
        class function GetRefCount: Integer;
        class function NewInstance: TObject; override;
        procedure FreeInstance; override;
      end;
    
    implementation
    
    { TGTSingleton }
    
    procedure TGTSingleton.FreeInstance;
    var
      i: PInteger;
    begin
      Dec(RefCount^);
      if RefCount^ = 0 then
        inherited;
    end;
    
    class function TGTSingleton.GetRefCount: Integer;
    // Van 'buitenaf' de refcount opvragen kan wel, maar moet
    // natuurlijk wel de echte counter afschermen
    begin
      Result := RefCount^;
    end;
    
    class function TGTSingleton.NewInstance: TObject;
    // De instance wordt ook bijgehouden in een 'static' variabele
    const
      Inst: TObject = nil;
    begin
      if RefCount^ = 0 then
        Inst := inherited NewInstance;
      Inc(RefCount^);
      Result := Inst;
    end;
    
    class function TGTSingleton.RefCount: PInteger;
    const
      RefCnt: Integer = 0;
    begin
      Result := @RefCnt;
    end;
    Last edited by GolezTrol; 11-Mar-06 at 19:15.
    1+1=b

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •