CreatingarealsingletonclassinDelphi5
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.
Creating a real singleton class in Delphi
by Lasse V錱s鎡her Karlsen, Systems Developer for Cintra Software Engineering
A singleton is a class that supports the creation of just one object. Its like your computer -- theres 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. Ive 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 proper singleton class that includes logic to enforce the 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 -- thats good -- but the programmer may also be unaware of the special nature of the class, which is bad. If you dont 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 : TSingleton;begin s1 := TSingleton.Create; s2 := TSingleton.Create; // Do something with s1 and s2 here s2.Free; s1.Free;end;(Ive left out the try...finally blocks and other safeguards for simplicitys sake.)
The goal is to make the TSingleton class behave in such a way that both s1 and s2 refer to the same object. Heres 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 its 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)
class function NewInstance: TObject; virtual;procedure FreeInstance; virtual;
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
Instance
so we know what it refers to. As for keeping track of how many references exist, we need another variable. We can it inside the class or make it a sort-of global like Instance
. Ill opt for the latter way but do what you feel is best. Ill name this variable Ref_Count
.
We now have two variables:
var Instance : TSingleton = nil; Ref_Count : Integer = 0;I initialize the variables so that initially they dont contain any garbage. I know that the compiler does this automatically, so this is just a readability issue.
Well 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 youll see that Ive put the declaration in the interface part of the unit so that its visible outside of it.
Heres the declaration of the TSingleton class:
type TSingleton = class public class function NewInstance: TObject; override; procedure FreeInstance; override; class function RefCount: Integer; end;I added the RefCount function so that we can see that it actually works, and its often handy to be able to read how many references to the object exist. Its not required, however, so you dont have to add it to your singleton classes if you dont need it.
Ok, now for the implementation of the three methods:
procedure TSingleton.FreeInstance;begin Dec( Ref_Count ); if ( Ref_Count = 0 ) then begin Instance := nil; // Destroy private variables here inherited FreeInstance; end;end;class function TSingleton.NewInstance: TObject;begin if ( not Assigned( Instance ) ) 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 thats it!
When you call TSingletons 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 returns that instance to the constructor so it will be reused
图片内容
最近更新
随机推荐
- 我用电脑黑了全世界(六十)
- 关停超过一周 苹果被黑事故过程回顾
- 云巢PC--后PC时代的领跑者
- 126万丹麦公民ID被泄露 蓝牙漏洞使An
- 正确互动才是聊天制胜关键,小鹿情感
- Oracle数据库系统修复多个安全漏洞列
- 赛门铁克63款产品曝漏洞 用户可被远程
- Hishop微信商城助力企业掘金6亿微信市
- MS10-015:Windows 内核中的漏洞可能允
- 铁总称未与任何网站合作代售保险
- MAXHUB新品登陆上海,定义未来智能会
- 我用电脑黑了全世界(九十五)
- Discuz!黑道生涯插件注射漏洞
- Alien Arena 2007远程格式串及拒绝服
- 微星携手迅雷网游加速器为游戏体验护
- 智利总统官方网站被黑客挂秘鲁国旗
- Sun Java运行环境时JDK/JRE安全更新修
- 以智能技术实时预测疫情传播 “摄星人
- 星际老玩家自筹赛事 老用户价值撬动“
- 微软:新安全补丁不要轻易升级