【问题标题】:class which attribute reference object type is same class属性引用对象类型为同一类的类
【发布时间】:2012-06-30 00:31:19
【问题描述】:

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

我不明白这个开发的功能是什么。编译器没问题,但是这段代码中没有无限引用?

例子:

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);
        }
    }

请你给我理解一下这个发展。

【问题讨论】:

  • 不,它在 static 构造函数中创建一个新实例,该实例只会运行一次。

标签: c# .net class types attributes


【解决方案1】:

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

还有一些你可能错过的东西,比如这个类型的实例构造函数必须是私有的,它自己的类是密封的等等。

所以你不能这样做

CachingServiceLocator  obj = new CachingServiceLocator() //not allowed

//to get the instance you have to do as following
CachingServiceLocator obj = CachingServiceLocator.me

Singleton Pattern

【讨论】:

  • 我已经学习了单例设计模式,但他不是这样设计的(以前最复杂)。这个实现它更基本。我知道这是它必须用于这种情况的静态构造函数规则。
猜你喜欢
  • 1970-01-01
  • 2021-06-19
  • 1970-01-01
  • 2019-08-23
  • 2015-11-13
  • 2023-04-08
  • 1970-01-01
  • 2017-09-14
  • 2020-10-03
相关资源
最近更新 更多