Creating a real singleton class in Delphi 5[3]

[入库:2005年8月18日] [更新:2007年3月24日]

本文简介:选择自 musicwind 的 blog

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 lasse@cintra.no.

happy programming!

更多文章

本文关键:Creating a real singleton class in Delphi 5
  相关方案
Google
 

本站最佳浏览方式为 分辨率 1024x768 IE 6.0(或更高版本的 IE浏览器)

go top