Creating a real singleton class in Delphi 5

设计模式 专栏收录该内容
3 篇文章 0 订阅

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

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 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 -- that's good -- but the programmer may also be unaware of the special nature of the class, which is bad. If you don't 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;
  s1, s2 : TSingleton;
  s1 := TSingleton.Create;
  s2 := TSingleton.Create;
  // Do something with s1 and s2 here
(I've left out the try...finally blocks and other safeguards for simplicity's sake.)

The goal is to make the TSingleton class behave 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;
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:

  1. Keep track of each existing instance of our class
  2. Keep track of how many references there are to this instance
  3. Create a new object only when no instance exists
  4. 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 won't 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 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. I'll opt for the latter way but do what you feel is best. I'll name this variable Ref_Count.

We now have two variables:

  Instance  : TSingleton  = nil;
  Ref_Count : Integer     = 0;
I initialize the variables so that initially they don't contain any garbage. 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:

  TSingleton = class
    class function NewInstance: TObject; override;
    procedure FreeInstance; override;
    class function RefCount: Integer;
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 don't have to add it to your singleton classes if you don't need it.

Ok, now for the implementation of the three methods:

procedure TSingleton.FreeInstance;
  Dec( Ref_Count );
  if ( Ref_Count = 0 ) then
    Instance := nil;
    // Destroy private variables here
    inherited FreeInstance;

class function TSingleton.NewInstance: TObject;
  if ( not Assigned( Instance ) ) then
    Instance := inherited NewInstance;
    // Initialize private variables here, like this:
    //   TSingleton(Result).Variable := Value;
  Result := Instance
  Inc( Ref_Count );

class function TSingleton.RefCount: Integer;
  Result := Ref_Count;
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 returns that instance to the constructor so it will be reused.

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.

Simplicity itself

As you can see, creating a singleton class doesn't 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 guarantees.

Before I give you the file to play with, let me give you a few words of warning.

  • Don't 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. Don't go down that road!
  • You can't make singleton components for the simple reason of ownership. A component is owned by a form and one component can't be owned by several other components.
  • Remember that the constructor and destructor get called for each new reference as they are created and destroyed. Don't initialize private variables in the constructor and don't 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 initialization 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

Happy programming!



  • 0
  • 0
  • 0
  • 一键三连
  • 扫一扫,分享海报

<p> <span style="font-size:14px;color:#337FE5;">【为什么学爬虫?】</span> </p> <p> <span style="font-size:14px;">       1、爬虫入手容易,但是深入较难,如何写出高效率的爬虫,如何写出灵活性高可扩展的爬虫都是一项技术活。另外在爬虫过程中,经常容易遇到被反爬虫,比如字体反爬、IP识别、验证码等,如何层层攻克难点拿到想要的数据,这门课程,你都能学到!</span> </p> <p> <span style="font-size:14px;">       2、如果是作为一个其他行业的开发者,比如app开发,web开发,学习爬虫能让你加强对技术的认知,能够开发出更加安全的软件和网站</span> </p> <p> <br /> </p> <span style="font-size:14px;color:#337FE5;">【课程设计】</span> <p class="ql-long-10663260"> <span> </span> </p> <p class="ql-long-26664262" style="font-size:11pt;color:#494949;"> 一个完整的爬虫程序,无论大小,总体来说可以分成三个步骤,分别是: </p> <ol> <li class="" style="font-size:11pt;color:#494949;"> 网络请求:模拟浏览器的行为从网上抓取数据。 </li> <li class="" style="font-size:11pt;color:#494949;"> 数据解析:将请求下来的数据进行过滤,提取我们想要的数据。 </li> <li class="" style="font-size:11pt;color:#494949;"> 数据存储:将提取到的数据存储到硬盘或者内存中。比如用mysql数据库或者redis等。 </li> </ol> <p class="ql-long-26664262" style="font-size:11pt;color:#494949;"> 那么本课程也是按照这几个步骤循序渐进的进行讲解,带领学生完整的掌握每个步骤的技术。另外,因为爬虫的多样性,在爬取的过程中可能会发生被反爬、效率低下等。因此我们又增加了两个章节用来提高爬虫程序的灵活性,分别是: </p> <ol> <li class="" style="font-size:11pt;color:#494949;"> 爬虫进阶:包括IP代理,多线程爬虫,图形验证码识别、JS加密解密、动态网页爬虫、字体反爬识别等。 </li> <li class="" style="font-size:11pt;color:#494949;"> Scrapy和分布式爬虫:Scrapy框架、Scrapy-redis组件、分布式爬虫等。 </li> </ol> <p class="ql-long-26664262" style="font-size:11pt;color:#494949;"> 通过爬虫进阶的知识点我们能应付大量的反爬网站,而Scrapy框架作为一个专业的爬虫框架,使用他可以快速提高我们编写爬虫程序的效率和速度。另外如果一台机器不能满足你的需求,我们可以用分布式爬虫让多台机器帮助你快速爬取数据。 </p> <p style="font-size:11pt;color:#494949;">   </p> <p class="ql-long-26664262" style="font-size:11pt;color:#494949;"> 从基础爬虫到商业化应用爬虫,本套课程满足您的所有需求! </p> <p class="ql-long-26664262" style="font-size:11pt;color:#494949;"> <br /> </p> <p> <br /> </p> <p> <span style="font-size:14px;background-color:#FFFFFF;color:#337FE5;">【课程服务】</span> </p> <p> <span style="font-size:14px;">专属付费社群+定期答疑</span> </p> <p> <br /> </p> <p class="ql-long-24357476"> <span style="font-size:16px;"><br /> </span> </p> <p> <br /> </p> <p class="ql-long-24357476"> <span style="font-size:16px;"></span> </p>
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页
钱包余额 0