miltone
miltone

Reputation: 4756

class which attribute reference object type is same class

I want to analyse a source code which give me for evolution. In this code, I have a class which attribute type is that the same type of this same class.

I don't understand what is the function of this development. The compiler is OK but there is a infinity reference in this code no ?

Example:

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

Can you give me to understand this development please.

Upvotes: 1

Views: 121

Answers (1)

Anand
Anand

Reputation: 14935

This is classic implementation of Singleton Pattern. In this way its made sure, only one object is created for this class type(for example logger, configuration classes generally are made singleton)

There are other things which you probably missed, like the instance constructor for this type must be private, the class it self is sealed etc.

So you can not do this

CachingServiceLocator  obj = new CachingServiceLocator() //not allowed

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

Singleton Pattern

Upvotes: 2

Related Questions