Author: Max Kleiner
Classes which can't support TPersistent or TPersistentClass had to implement
another technique to manage the creation of obejcts at runtime
Answer:
If a class inherits from TPersistent we can use RegisterClass in several units so
we can use the function GetClass to convert a class name to a class instance:
1 TFinanceClass = classof TFinance;
2 3 var4 refClass: TFinanceClass;
5 6 refClass := TFinanceClass(getClass(values['RegClass']));
7 dynObj := refClass.Create;
8 dynObj.getCharge(9.2);
9 10 RegisterClass(TFinance);
If you can't inherit from TPersistent we can use a "Name=Value" pair of objects in
a stringlist and loaded when a module is created or by user events. So you can
determine which object should be created.
11 function initObjinList;
12 var//refClass: TFinanceClass;13 dynObj: TFinance;
14 myClsname: string[240];
15 begin16 with TStringList.Create do17 begin18 clear;
19 values['RegClass'] := 'TRegularCharge2';
20 values['PrefClass'] := 'TPreferredCharge2';
21 values['TrialClass'] := 'TTrialCharge2';
22 myClsname := 'TrialClass';
23 if indexofname(myClsname) > -1 then24 begin25 {refClass:= TFinanceClass(getClass(values['RegClass']));26 dynObj:= refClass.Create;27 dynObj.getCharge(9.2); }28 case IndexOfname(myClsname) of29 0: dynObj := TRegularCharge2.create;
30 1: dynObj := TPreferredCharge2.create;
31 2: dynObj := TTrialCharge2.create;
32 end;
33 dynObj.getcharge(9.1);
34 dynObj.Free;
35 result := true;
36 end;
37 Free;
38 end;
39 end;
The value is the class type and the name simplifies the maintainability of the
classes.
syntax:
40 mystringlist.values[name] := value //write41 myname := mystringlist.values[name] //read
I made only one function to show the simplicity but registering classes in a
StringList and choosen from a case of structure should be separated in differnt
functions.
All the classes inherit from TFinance and in comparison to RegisterClass we don't
use a ClassReference.
Descendants override the public or protected getCharge() methods to perform their
actions.
42 TFinance = class43 public44 function getCharge(const Balance: double): double; virtual;
45 abstract;
46 end;
47 48 TRegularCharge2 = class(TFinance)
49 public50 function getCharge(const Balance: double): double; override;
51 end;
52 53 TPreferredCharge2 = class(TFinance)
54 public55 function getCharge(const Balance: double): double; override;
56 end;
57 58 TTrialCharge2 = class(TFinance)
59 public60 function getCharge(const Balance: double): double; override;
61 end;