There are certain situations where there has to be one and only one instance of a class (or any component) in a problem domain. The best practice in these situations is to let the class itself to manage its instantiation process, this pattern of creational behavior is called Singleton.This pattern is not necessary related to a class. for example in COM there are situations where we need to have one instance of a COM component, this component can be a collection of classes, still this is called Singleton
Depending on the language there are different ways to implement this pattern. The only common point is that it is implemented by the class itself, and it is the class itself that manipulates its instantiation process. All the client requests for instantiation will go through one particular channel and will end-up in retrieving one similar instance. The first request for instance retrieval will cause instantiation, the subsequent requests will retrieve the already created instance. C++- The constructor of the class must be either private or protected, by making it non-public any attempt for regular instantiation will fail.
- There must be one Instance method that builds the instance for the first time or returns the same instance if it already exists. This instance method must be static for one good reason, we can’t call it from an instance variable because there is no way to have instance variables! It must be a member of the class because it needs to access the private constructor.
- There is one member instance of the class that is defined static so it is accessible to the static instance method Class
/////////Header File class ASingleInstanceClass { private://To seal the class ASingleInstanceClass() { } public: static ASingleInstanceClass* GetInstance(); private: static ASingleInstanceClass* m_instance; }; ////////////CPP File #include "ASingleInstanceClass.h" ASingleInstanceClass* ASingleInstanceClass::m_instance = NULL; ASingleInstanceClass* ASingleInstanceClass::GetInstance() { if(m_instance == NULL) { m_instance = new ASingleInstanceClass; } return m_instance; } C# We can employ the same approach in C# to create a singleton class; however C# has this new capability called static constructors that can be used insteadpublic sealed class ASingleInstanceClass { static readonly ASingleInstanceClass instance = new ASingleInstanceClass(); static ASingleInstanceClass() { } ASingleInstanceClass() { } public static ASingleInstanceClass Instance { get { return instance; } } }
No comments:
Post a Comment