Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>When evaluating the Singleton pattern, you have to ask "What's the alternative? Would the same problems happen if I didn't use the Singleton pattern?"</p> <p>Most systems have some need for <i>Big Global Objects</i>. These are items which are large and expensive (eg Database Connection Managers), or hold pervasive state information (for example, locking information). </p> <p>The alternative to a Singleton is to have this Big Global Object created on startup, and passed as a parameter to all of the classes or methods that need access to this object.</p> <p>Would the same problems happen in the non-singleton case? Let's examine them one by one:</p> <ul> <li><p><b>Memory Management</b>: The Big Global Object would exist when the application was started, and the object will exist until shutdown. As there is only one object, it will take up exactly the same amount of memory as the singleton case. Memory usage is not an issue. <i>(@MadKeithV: Order of destruction at shutdown is a different issue).</i></p></li> <li><p><b>Multithreading and bottlenecks</b>: All of the threads would need to access the same object, whether they were passed this object as a parameter or whether they called <i>MyBigGlobalObject.GetInstance()</i>. So Singleton or not, you would still have the same synchronisation issues, (which fortunately have standard solutions). This isn't an issue either.</p></li> <li><p><b>Unit testing</b>: If you aren't using the Singleton pattern, then you can create the Big Global Object at the start of each test, and the garbage collector will take it away when the test completes. Each test will start with a new, clean environment that's unnaffected by the previous test. Alternatively, in the Singleton case, the one object lives through ALL of the tests, and can easily become "contaminated". So yes, the Singleton pattern really <i>bites</i> when it comes to unit testing.</p></li> </ul> <p>My preference: because of the unit testing issue alone, I tend to avoid the Singleton pattern. If it's one of the few environments where I don't have unit testing (for example, the user interface layer) then I <i>might</i> use Singletons, otherwise I avoid them.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload