Design patterns that will be covered in this article:
- Singleton
The Singleton pattern restricts a class to only 1 instance. Every reference to the class refers to the same underlying instance. Singleton is categorized as a creational pattern because the design pattern is all about creating a shared instance.
The Singleton Plus pattern is also common, which provides a shared or default Singleton instance but it also allows other instances to be created too.
- Use the Singleton pattern when having more than 1 instance of a class would cause problems or when it just wouldn't make logical sense
- Use the Singleton Plus pattern if a shared instance is useful most of the time, but you also want to allow custom instances to be created
- An example of a Singleton Plus pattern is File Manager (this handles everything to do with file system access)
- There is a default instance, which is a Singleton or you can create your own (for instance, on a background thread)
- The Singleton pattern is very easy to overuse
- It's not recommended to use Singletons if you're simply trying to pass information from 1 view controller to another
- If you do determine you actually do need a Singleton, consider whether or not a Singleton Plus would make more sense. If a Singleton really is best, prefer to use a Singleton plus over a Singleton
- Testing is a common reason why Singletons are problematic - if you have a state being stored in a global object like a Singleton, then order of tests can matter and it can be painful to unlock them
- Be careful of "code smells" which means that your use case isn't appropriate as a Singleton at all