Creating a real singleton class in Delphi 5

zhaozj2021-02-11  173

Creating a real singleton class in Delphi 5

Abstract: The article describes how to create a class that follows the singleton pattern The class described will take care of the singleton requirements and effects itself, effectively leaving the programmer to use the class as any others..

CREANG A REAL SINGLETON CLASS in Delphi

By lasse v 錱 s 镃 HER Karlsen, Systems Developer for Cintra Software Engineering

Errata1.Implementation of TSingleton.NewInstance had the first test switched, the one that checked if the Instance variable was assigned or not -. Fixed 11-08-2000 - Thanks to the people that emailed me about this --2.Overzealous fix For The First Errata, The NewInstance Method Should Now Work As Stated. - Fixed 11.08.2000 -

A singleton is a class that supports the creation of just one object It's like your computer -.. There's just one keyboard So if you were writing Delphi code that simulated your computer, you would want just one object instance to deal with keyboard read, Write, And Control Activities.

Articles About Singleton Classes Are Rare But There Are A Few on The Internet. I've seen some in magazines Too. But None of these Articles include Sample Code to Create a real singleton class.

By "real" I mean that the class itself enforces the one-instance requirement, instead of leaving that task to the programmer. All of the articles I have seen so far have required the programmer to use the class in a special way to enforce the Singleton Pattern.

In this article you will see how to create a properties singleton class what one-instance rule.

Note: The conventional approach, in which the one-instance rule is maintained explicitly by the programmer, is not without merit Real singleton classes like the one I present here effectively hide the details and awareness of the singleton pattern from the programmer The programmer.. is relieved of the task of enforcing the pattern - that's good - but the programmer may also be unaware of the special nature of the class, which is bad If you do not know that the class is a singleton class then all sorts. Of errors can crop up. You have been warned! Writing the code

Our Goal Is To Write a Class That CAN Be Used Like this:

Procedure test;

VAR

S1, S2: TSINGETON;

Begin

S1: = Tsingleton.create;

S2: = tsingleton.create;

// do Something with s1 and s2 here

S2.Free;

S1.Free;

END; (I'VE Left out the try ... finally block and other saffeguards for simplicity's set.)

THE Goal Is To Make In Such A Way That Both S1 And S2 Refer to the Same Object. Here's What We Have to do:

Instantiate the object the first time Create is called (when s1 is created above) Ensure that when another Create is executed (s2 above), the existing object is reused instead of another one created Avoid destroying the object when it's not the last reference that is destroyed (when s2 is freed) Destroy the instance when the last reference is destroyed (when s1 is freed above) Is there a way to override the creation and destruction of a new object in Delphi? there sure is. in the TObject class (the Mother of all objects {pun intended}, There Are Two Methods We can use:

Class function newinstance: TOBJECT; Virtual

Province.

NewInstance is responsible for allocating memory to hold a new instance of the class, and FreeInstance is responsible for freeing that memory when the class is through with it.These methods control what happens when the object is created and when the object is destroyed. If we Overwrite this code, We can alter the default behavior to work the say a singleton class requires. Nothing to it.

Tracking instances is a little trickier. We must:

Keep track of each existing instance of our class Keep track of how many references there are to this instance Create a new object only when no instance exists Destroy the object when the last reference is removed To keep track of an existing instance, we will use a global variable. Actually, the variable will ultimately be declared inside the Implementation part of a unit so it will not be a true global variable. But the scope must be sufficient to track all the Create and Free calls. We'll call the variable

Instance so we know what it refers.

As for keeping track of how much references exist, We can it.. IT-of global limited. I'll Opt for the latter. I ' Ll name this variable ref_count.

We now since:

VAR

Tsingleton = NIL;

Ref_count: integer = 0; I initialize the variables so what initially. I Know That The Compiler Does This Automatically, So this is Just A Readability Issue.

We'll need to declare the TSingleton class above the variable block, and if you take a look at the example files that you can download at the end of this article you'll see that I've put the declaration in the interface part of The Unit So That It's Visible Outside of It.here's The Declaration of The Tsingleton Class:

Type

Tsingleton = Class

public

Class Function Newinstance: TOBJECT; OVERRIDE

Excedure FreeInstance; Override;

Class Function Refcount: Integer;

end; I added the RefCount function so that we can see that it actually works, and it's often handy to be able to read how many references to the object exist It's not required, however, so you do not have to add it to. Your Singleton Classes if you don't need it.

OK, Now for the importation of the three methods:

Procedure tingsingleton.freeinstance;

Begin

Dec (ref_count);

IF (Ref_count = 0) THEN

Begin

= NIL;

// Destroy Private Variables Here

Inherited freeInstance;

END;

END;

Class Function Tsingleton.newinstance: TOBJECT

Begin

IF (Not Assigned) THEN

Begin

Instance: = inherited newinstance;

// Initialize Private Variables here: Like this:

// tsingleton (result) .variable: = value;

END;

Result: = Instance

INC (Ref_count);

END;

Class function tsingleton.refcount: integer;

Begin

Result: = Ref_count;

End; and that's it!

When you call TSingleton's constructor, a call is placed to the NewInstance method declared in TObject. This method allocates memory to hold the new object and returns it to the constructor. The constructor uses that memory and eventually returns a pointer to the memory to the code that called the constructor. This pointer is usually stored in a variable while the object is in use.I have overridden the NewInstance method so it will allocate the memory only if no instance of the class exists. If there is an existing instance, the function Simply return That Instance to the constructor so it will be reuse.

If we call the constructor three times, an object is created only the first time. The other two calls simply reuse the first object. The reference count variable let us know that we have three references to the single instance.

When the program calls the destructor, a call to FreeInstance is placed to free the memory allocated in the constructor. This method, too, is overridden so that the object is destroyed only when the last reference is removed.

If you intend to use a singleton in a multithreaded program, treat the object as you would any variable you share between threads Because that's just what you do:. Share it between the threads So you must take special care when changing data..

SIMPLITY ITSELF

As you can see, creating a singleton class does not require much effort, just the right knowledge and a few lines of code. My code works fine in Delphi 5. The technique will probably work fine with older versions of Delphi, but I haven 'T Tested It So I don't make any guarance.

Before I Give You The File to Play with, Let me Give You a few Words of Warning.

Do not descend from a singleton class. The reason for that is that there is only one instance and reference count variable. If you derive two classes from TSingleton, only one object will be created. The other class will reuse that object, which will be an instance of a different class. Do not go down that road! You can not make singleton components for the simple reason of ownership. A component is owned by a form and one component can not be owned by several other components. Remember that the constructor and destructor get called for each new reference as they are created and destroyed. do not initialize private variables in the constructor and do not free them in the destructor. Instead, build that code into the NewInstance and the FreeInstance methods , as shown in the comments. The order of adjusting ref_Count in the two methods in conjunction with the rest of the code in those two methods is critical. It has to do with proper creation and destruction when something goes wrong. If your in itialization code raises an exception, the order of doing things like shown above will make sure that the class is destroyed properly. Alter this code at your peril! The file that you can download is just a copy of the unit that declares the singleton class described In this article.link to file: CodeCentral Entry 15083.

I'm Sure You Can Find A Few Places WHERE A Singleton Class Comes in Handy and Now You Have The Tools To Create Your Own! If You Want To Get in Touch with Me, My Email Is Lasse@cintra.no.

Happy programming!

More articles

转载请注明原文地址:https://www.9cbs.com/read-5312.html

New Post(0)