Singleton Data Access Slots

At our data access level, we have this standard implementation, in which the class is accessible through a singleton public property that looks something like this:

public static CustomerController Instance
        {
            get 
            {
                lock(singletonLock)
                {
                    if( _instance == null )
                    {
                        _instance = new CustomerController();  
                    }
                    return _instance;
                }
            }
        }

Now, I understand what the code does, but I was wondering why you would do this by simply instantiating the class every time it is used?

+3
source share
3 answers

EDIT: Oh, ooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo But I have an example of this: if your multithreaded application combines all of your "database calls through singleton class, only one thread will ever access the database directly, avoiding race conditions."

, , ( , , , - ), . singleton logger class, - Logger, , Logger .

singleton, , FOR, .

+2

, , singleton

 public static CustomerController Instance
        {
                get 
                {
                        if( _instance == null )
                        {
                           lock(singletonLock)
                           {
                                if( _instance == null )
                                {
                                        _instance = new CustomerController();  
                                }

                            }
                        }   
                        return _instance;
                }
        }
+1

: , .

This gives you the benefits of being a global variable (i.e. just one) with the benefits of being an object of a class (among other things, it can do invisible initialization the first time it is needed).

+1
source

Source: https://habr.com/ru/post/1698948/


All Articles