Skip to content

Instantly share code, notes, and snippets.

@cloudiosx
Created March 28, 2022 01:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cloudiosx/991a06acfaa2721703d94541a41f9a52 to your computer and use it in GitHub Desktop.
Save cloudiosx/991a06acfaa2721703d94541a41f9a52 to your computer and use it in GitHub Desktop.

Introduction

Design patterns that will be covered in this article:

  • Singleton

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.

Singleton Plus

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.

When Should You Use It?

  • 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)

What Should You Be Careful About?

  • 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

Code

AnimeSettings.swift

Screen Shot 2022-03-27 at 9.21.51 PM.png

AnimeSettingsViewController.swift

Screen Shot 2022-03-27 at 9.22.37 PM.png

Main.storyboard

Screen Shot 2022-03-27 at 9.23.11 PM.png

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment