Delphi - Global Objects

There are a number of classes that should only be instantiated once and then used globally. Many times these are used to maintain a dynamic list of some type.

There are 2 techniques

Examples of both types can be found in the Delphi source - according to the following comment from printers.pas, both methods work, but the function calls create a smaller exe.

Overview | Examples | Naming Conventions


Overview

In the table below, the variables are created in the initialization section, the functions create the objects the first time they are called. There are many additional examples - but this is enough to get the idea.


Examples

The example code below is taken from the supplied Delphi source files. In some cases, I have added spaces and comments to make it more readable. The only common item is that In the first two In the third


Clipboard

The following code defines a global function to access the clipboard. The comments are mine. Many of the source files have something similar to or it is assigned where the variable is defined (see the next example). Since that is the default, I have no idea why they do this explicitly!


Printers


TGraphics

The Graphics unit uses the following mechanism to extend the supported formats at run time. Notice that RegisterFileFormat is a class method that does not require an object to call it.

This is how the JPEG unit adds itself to the list of supported TGraphics types.


Menus

The Menus unit still uses the old technique - global variables instead of functions. (Reformatted to improve readability.)


Naming Conventions

These are a couple of examples I wrote .. showing how I added the mc identifier (from my Naming Convention suggestions).

From unit mcExtras,

mc_LogFiles is one of the exceptions. In this case, I placed the underscore in the unit name / filename and used a global variable (instead of a function) to access it. I haven't decided which method to access the object is "best", but I have decided to use the underscore for the objects and to omit it for the class.


Author: Robert Clemenzi
URL: http:// mc-computing.com / Languages / Delphi / Global_Objects.html