Class/Static Constants in Delphi

前端 未结 9 883
粉色の甜心
粉色の甜心 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:36

     TMyObject = class
        private
          class var FLogger : TLogLogger;
          procedure SetLogger(value:TLogLogger);
          property Logger : TLogLogger read FLogger write SetLogger;
        end;
    
    procedure TMyObject.SetLogger(value:TLogLogger);
    begin
      // sanity checks here
      FLogger := Value;
    end;
    

    Note that this class variable will be writable from any class instance, hence you can set it up somewhere else in the code, usually based on some condition (type of logger etc.).

    Edit: It will also be the same in all descendants of the class. Change it in one of the children, and it changes for all descendant instances. You could also set up default instance handling.

     TMyObject = class
        private
          class var FLogger : TLogLogger;
          procedure SetLogger(value:TLogLogger);
          function GetLogger:TLogLogger;
          property Logger : TLogLogger read GetLogger write SetLogger;
        end;
    
    function TMyObject.GetLogger:TLogLogger;
    begin
      if not Assigned(FLogger)
       then FLogger := TSomeLogLoggerClass.Create;
      Result := FLogger;
    end;
    
    procedure TMyObject.SetLogger(value:TLogLogger);
    begin
      // sanity checks here
      FLogger := Value;
    end;
    

提交回复
热议问题