Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Singleton class vs. class with static member

Despite the many threads on that topic, I am still unclear as to when to choose which approach. I am hoping that by discussing a specific example, I will finally "get it."

Note: My language here is Cocoa though the general issue is not language-specific.

I have a class TaskQueue that I want to use to:

  • access from anywhere in my code in order to add or remove scheduled tasks
  • process automatically the scheduled tasks at regular intervals

When TaskQueue is first used, I want TaskQueue to initiate a thread that will then wake up at regular intervals to process the tasks.

Obviously, I will need at a minimum two variables:

  • an array to store the tasks
  • an instance of the thread processing the tasks

Since I only want one queue of tasks and one thread to process these tasks, I have two choices:

  1. Make TaskQueue a singleton class (using for example CWL_DECLARE_SINGLETON_FOR_CLASS_WITH_ACCESSOR as described in http://www.cocoawithlove.com/2008/11/singletons-appdelegates-and-top-level.html, which I believe I will have to modify the CWLSynthesizeSingleton.h file to start the thread at init time.)

  2. Have the array of tasks and the thread instance both be static (following the approach suggested here: How do I declare class-level properties in Objective-C?)

Is there clearly one approach that's better than the other one in this specific case? If so, why?

like image 282
Lolo Avatar asked Dec 31 '12 05:12

Lolo


1 Answers

The main differences are simple things like:

  • with a singleton you can pass around the object for delegates and callbacks
  • with a singleton you can implement interfaces and derive it
  • with a singleton you can use a factory pattern to build up your instance

If you don't need any of them, as with global functionality that must be accessed all around your code then you can go with static methods.

I personally prefer using static methods unless I have an explicit reason to use a singleton instance (such as having a common interface but different implementations).

Mind the fact that refactoring static methods to a singleton instance is quite a straightforward process so if you ever find the need for the latter you will refactor it easily (then you have the C preprocessor, a single #define would be almost enough).

like image 72
Jack Avatar answered Oct 20 '22 20:10

Jack