Author: Jorge Abel Ayala Marentes
When you dinamically create objects at runtime, you need to check that you free
those objects too. Class methods can help in the process.
Answer:
Class Methods aply to the class level, in other words you donīt need an instance to
call the method
I wish we could define class objects as well, but they doesnīt exist in Object
Pascal, so we will do a trick, we are going to define a variable in the
implementation section of the unit, this variable will hold the number of instances
the class will have in a moment in time. Object Oriented purist might claim about
it, but it works, nobody is perfect (not even Delphi!).
For example say you need to create instances of a class named TFoo, so you create
the following Unit.
We will define two class procedures: AddInstance(to increse the counter of
instances) and ReleaseInstance(to decrese the number of instances), these are
called in the constructor and the destructor acordingly. Finally we define a class
function NumOfInstances which returns the actual number of instances.
Add a Initilialization and a Finalization section to the Unit, in the Finalization
section ask if the number of instances is <> 0, if this is the case you known that
you didinīt destroy all the objects that you created.
1 unit U_Foo;
2
3 interface
4
5 uses
6 Classes, Windows, SysUtils;
7
8 type
9 TFoo = class
10 private
11 class procedure AddInstance;
12 class procedure ReleaseInstance;
13 public
14 constructor Create;
15 destructor Destroy; override;
16 class function NumOfInstances: Integer;
17 end;
18
19 implementation
20
21 var
22 TFoo_Instances: Integer = 0;
23
24 { TFoo }
25
26 class procedure TFoo.AddInstance;
27 begin
28 Inc(TFoo_Instances);
29 end; //end of TFoo.AddInstance
30
31 constructor TFoo.Create;
32 begin
33 AddInstance;
34 end; //end of TFoo.Create
35
36 destructor TFoo.Destroy;
37 begin
38 ReleaseInstance;
39 inherited;
40 end; //end of TFoo.Destroy
41
42 class function TFoo.NumOfInstances: Integer;
43 begin
44 Result := TFoo_Instances;
45 end; //end of TFoo.NumOfInstances
46
47 class procedure TFoo.ReleaseInstance;
48 begin
49 Dec(TFoo_Instances);
50 end; //end of TFoo.ReleaseInstance
51
52 initialization
53
54 finalization
55
56 if TFoo_Instances <> 0 then
57 MessageBox(0,
58 PChar(Format('%d instances of TFoo active', [TFoo_Instances])),
59 'Warning', MB_OK or MB_ICONWARNING);
60
61 end.
|