Application scenarios

During the program run cycle, there is a globally callable object. In this case, you need to use the singleton implementation.

API and language

Swift

Core logic/code

Simple interest needs to meet the following requirements:

  • You can call — static globally to modify objects created by this class, because objects modified by STAITC are stored in the global area and are not passively destroyed throughout the life of the program
  • There is only one object globally — the initialization function is set to private, ensuring that this singleton object can only be created by itself.

Why use the static modifier in a singleton?

  1. Static modifiers are global variables, because they can be accessed directly through the class name/structure name, etc
  2. Global variable properties are lazily loaded by default. In the case of global variables, it is obvious that the program is not loaded as soon as it is started, so it should be loaded when needed.

The sample code

// Create a singleton
class Base {
    static let `default` = Base(a)private init(a) {}
    
    var age = 4
}

/ / call
Base.default.age = 5
Copy the code