Delphi Application GetClass and RegisterClass example

Source: Internet
Author: User


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.


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.