Using GetClass and registerclass enables you to instantiate specific subclasses based on strings, which can be useful for situations where dynamic configuration programs are required. Other applications such as subform switching, algorithm substitution, etc. can be applied.
Unit Example1;
Interface
Uses
Windows, Messages, sysutils, variants, Classes, Graphics, Controls, Forms,
Dialogs, Stdctrls;
Type
TForm1 = Class (Tform)
Button1:tbutton;
Procedure Button1Click (Sender:tobject);
Private
Public
End
ILog = Interface (IUnknown)
[' {a65044fc-644c-482a-bbff-50a618835fc6} ']
Procedure Writemessage;
End
TLog = Class (Tinterfacedpersistent, ILog)
Public
class function CreateInstance (name:string): TLog; overload;
Procedure Writemessage; Virtual Abstract
End
Ttextlog = Class (TLog)
Public
Procedure Writemessage; Override
End
Txmllog = Class (TLog)
Public
Procedure Writemessage; Override
End
Tnulllog = Class (TLog)
Public
Procedure Writemessage; Override
End
Var
Form1:tform1;
Implementation
{$R *.DFM}
Procedure Tform1.button1click (Sender:tobject);
Var
Log:tlog;
Begin
{The actual application can read the string from the configuration to determine the instantiation of the specific subclass}
Log: = tlog.createinstance (' Txmllog ');
If assigned (LOG) then
Begin
Log.writemessage;
Log.free;
End
End
class function Tlog.createinstance (name:string): TLog;
Var
Aclass:tpersistentclass;
Begin
Result: = nil;
AClass: = GetClass (Name);
If assigned (AClass) then
Begin
Result: = Aclass.newinstance as TLog;
Result.create;
End
Else
{Error Handle}
End
{Ttextlog}
Procedure Ttextlog.writemessage;
Begin
Writing to a text file
End
{Txmllog}
Procedure Txmllog.writemessage;
Begin
Write to XML file
End
{Tnulllog}
Procedure Tnulllog.writemessage;
Begin
{Nothing need to do}
End
Initialization
RegisterClass (Ttextlog);
RegisterClass (Txmllog);
RegisterClass (Tnulllog);
Finalization
Unregisterclass (Ttextlog);
Unregisterclass (Txmllog);
Unregisterclass (Tnulllog);
End.