使用D2009和D2010的新功能在Delphi中创建单例 [英] Creating a singleton in Delphi using the new features of D2009 and D2010

查看:77
本文介绍了使用D2009和D2010的新功能在Delphi中创建单例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望在Delphi中创建一个单例。在使用较旧版本的Delphi之前,我已经完成了此操作,最后使用了全局变量(在实现部分中),并使用初始化和终结处理实例。此外,由于无法隐藏标准构造函数,因此无法阻止用户创建实例。我想知道是否有任何新功能(例如类构造函数和析构函数以及类变量(好的,不是那么新),也许是泛型)可以帮助创建泛型单例类。我还没有创造出令我满意的东西。

I'm looking to create a singleton in Delphi. I've done this before using older versions of Delp and ended up using global variables (in the implementation section) and using initialization and finalization to take care of the instance. Also there was no way of preventing the user from creating an instance as you couldn't hide the standard constructor. I was wondering if any of the new features such as class constructors and destructors, and class variables (ok, not so new), perhaps generics, could help in creating a generic singleton class. I haven't managed to create something to my satisfaction yet.

推荐答案

可以通过覆盖TRUE分配器和Delphi, NewInstance FreeInstance 中的deallocator方法。

It was possible to manage this by overriding the TRUE allocator and deallocator methods in Delp NewInstance and FreeInstance. Constructors and Destructors in Delphi only initialise and finalise respectively, they do not allocate or deallocate memory, so attempting to hide constructors was always a little misguided.

i.e。在Delphi中,构造函数和析构函数只能分别初始化和完成,它们不会分配或取消分配内存,因此尝试隐藏构造函数总是有点误导。只要您覆盖 NewInstance ,以便它只返回对类的一次内存分配的引用,就可以允许任意使用所有构造函数。

i.e. it was possible to allow free use of any and all constructors as long as you overrode NewInstance such that it only ever returned a reference to one single allocation of memory for the class.

但是尝试在基类中强制使用/行为模式是错误的恕我直言。并非所有模式都是或不需要特定的类来封装该模式。

But attempting to enforce a usage/behavioural pattern in a base class is a mistake imho. Not ALL patterns are or require specific classes to encapsulate the pattern.

在这种情况下,您最终会创建不必要的复杂内容,并且复杂性会吸引我的经验然后,练习的目的便是试图发现模式实现中的缺陷,然后尝试实施针对这些缺陷的防护措施,而不是继续进行单例类应该执行的实际工作。

In cases such as this you end up creating something that is needlessly complicated, and complication attracts errors in my experience and the object of the exercise then becomes trying to find flaws in the pattern implementation and then trying to implement safeguards against those flaws, rather than getting on with the practical job of work that the singleton class was supposed to perform.

到目前为止,FAR更简单,更有效地记录了类的用法。

It is far, FAR simpler and more effective to document the USAGE of the class.

文档是一种实现此模式的技术例如,对于VCL中的 Application Screen 对象,它已经完美地工作了15年,更不用说我在那几年创建的无数其他单例了。

Documentation as a technique for implementing this pattern has worked flawlessly for 15 years for the Application and Screen objects in the VCL, for example, not to mention countless other singletons that I've created in those years.

这篇关于使用D2009和D2010的新功能在Delphi中创建单例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆