The Laze Getter pattern
To save resources, it is inevitable to not create the maybe required object at startup. But of course we need to create it, when it is needed. To reach this, the Lazy Getter method is used as a synonyme for the late created object in the source code. This method does nothing else than looking, if the object is created - if yes, then return it - or not - then create and return it. That's all. A simple basic pattern.
Example for Java:
// somewhere you have declared a public variable of type MessageBox
public MessageBox instance;
...
// You define a Lazy Getter method that cares for its instantiation
private MessageBox getMessageBox(String message)
{
if (instance == null)
instance = new MessageBox();
instance.setMessage( message );
instance.pack();
}
...
// later you use getMessageBox() instead of a direct variable call
getMessageBox("Hello").show();
// that's it ...
public MessageBox instance;
...
// You define a Lazy Getter method that cares for its instantiation
private MessageBox getMessageBox(String message)
{
if (instance == null)
instance = new MessageBox();
instance.setMessage( message );
instance.pack();
}
...
// later you use getMessageBox() instead of a direct variable call
getMessageBox("Hello").show();
// that's it ...
Example for Lazarus / Delphi and language hint
Language hint:In Lazarus and Delphi there is one thing more to consider. During Java has a Garbage Collector that cares for freeing resources again after their instatntiation, in Lazarus and Delphi the programmer has to care for. And of course a Laze Getter caan't handle disallocation and destruction of objects.
A proper section for freeing resources in window-applications is the BeforeDestruction method of your class. There You should NOT use the way, always shown on the web (fTimer.Free; fTimer := nil;) but the method call to FreeAndNil: FreeAndNil(fTimer);, because this methods has exactly this one purpose and I recommend to use it.
// in the declaration part, You have defined a public variable
public
...
fTime: TTimer;
...
// somewhere in the code, You implement the Getter:
function getTimer(): TTimer;
begin
if not assigned(fTimer) then
fTimer := TTimer.Create();
result := fTimer;
end;
...
// somwhere else you use the Lazy Getter
...
getTimer().Enabled = true;
...
// before end of the program you have to free the resources again
FreeAndNil(fTimer);
// that's it ...
public
...
fTime: TTimer;
...
// somewhere in the code, You implement the Getter:
function getTimer(): TTimer;
begin
if not assigned(fTimer) then
fTimer := TTimer.Create();
result := fTimer;
end;
...
// somwhere else you use the Lazy Getter
...
getTimer().Enabled = true;
...
// before end of the program you have to free the resources again
FreeAndNil(fTimer);
// that's it ...
Kommentare
Kommentar veröffentlichen