Class/Static Constants in Delphi
delphi
Solution
Here is how I'll do that using a class variable, a class procedure and an initialization block:
unit MyObject;
interface
type
TMyObject = class
private
class var FLogger : TLogLogger;
public
class procedure SetLogger(value:TLogLogger);
class procedure FreeLogger;
end;
implementation
class procedure TMyObject.SetLogger(value:TLogLogger);
begin
// sanity checks here
FLogger := Value;
end;
class procedure TMyObject.FreeLogger;
begin
if assigned(FLogger) then
FLogger.Free;
end;
initialization
TMyObject.SetLogger(TLogLogger.Create);
finalization
TMyObject.FreeLogger;
end.
Problem
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: ``` public class MyObject { private static final MySharedObject mySharedObjectInstance = new MySharedObject(); } ``` Or, if MySharedObject needed more complicated initialization, in Java I could instantiate and initialize it in a static initializer block. (You might have guessed... I know my Java but I'm rather new to Delphi...) Anyway, I don't want to instantiate a new MySharedObject each time I create an instance of MyObject, but I do want a MySharedObject to be accessible from each instance of MyObject. (It's actually logging that has spurred me to try to figure this out - I'm using Log4D and I want to store a TLogLogger as a class variable for each class that has logging functionality.) What's the neatest way to do something like this in Delphi?