类,其属性引用对象类型为同一类



我想分析一个源代码,它给了我进化。在此代码中,我有一个类,其属性类型是同一类的相同类型。

我不明白这种发展的功能是什么。编译器没问题,但此代码中有无穷大引用没有?

例:

public sealed class CachingServiceLocator : IDisposable
{
    private Hashtable cache; /// Le cache des références vers les services métiers
    private static volatile CachingServiceLocator me; /// L'unique instance du Service Locator
    /// Le constructeur statique
    static CachingServiceLocator()
    {
        try
        {
            me = new CachingServiceLocator();
        }
        catch (Exception)
        {
            MessageBox.Show("Impossible de créer le service locator...nVeuillez accepter toutes nos excuses pour le désagrément occasionné..." , "Service Locator !", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
    }

你能让我了解一下这个发展吗?

这是单例模式的经典实现。通过这种方式,它确保只为此类类型创建一个对象(例如记录器,配置类通常成为单例)

您可能还错过了其他内容,例如这种类型的实例构造函数必须是私有的,它本身的类是密封的等。

所以你不能这样做

CachingServiceLocator  obj = new CachingServiceLocator() //not allowed
//to get the instance you have to do as following
CachingServiceLocator obj = CachingServiceLocator.me

单例模式

最新更新