Class/Static Constants in Delphi

前端 未结 9 730
粉色の甜心
粉色の甜心 2021-02-05 12:06

In Delphi, I want to be able to create an private object that\'s associated with a class, and access it from all instances of that class. In Java, I\'d use:

pub         


        
9条回答
  •  [愿得一人]
    2021-02-05 12:30

    Well, it's not beauty, but works fine in Delphi 7:

    TMyObject = class
    pulic
        class function MySharedObject: TMySharedObject; // I'm lazy so it will be read only
    end;
    
    implementation
    

    ...

    class function MySharedObject: TMySharedObject;
    {$J+} const MySharedObjectInstance: TMySharedObject = nil; {$J-} // {$J+} Makes the consts writable
    begin
        // any conditional initialization ...
       if (not Assigned(MySharedObjectInstance)) then
           MySharedObjectInstance = TMySharedOject.Create(...);
      Result := MySharedObjectInstance;
    end;
    

    I'm curently using it to build singletons objects.

提交回复
热议问题