I have a singleton class MyClass
for management work with third party sdk. Inside singleton I have init
method.
My question is : does init
method called every time I call something from singleton like MyClass.shared.mymethod()
or in order to call init I have to call var instance = MyClass()
?
If you have a regular object that you can't deinitialize it's a memory problem. Singletons are no different, except that you have to write a function to do it. Singletons have to be completely self managed. This means from init to deinit.
Singleton is a creational design pattern, which ensures that only one object of its kind exists and provides a single point of access to it for any other code. Singleton has almost the same pros and cons as global variables. Although they're super-handy, they break the modularity of your code.
Singleton Class in Java using Lazy LoadingThe instance could be initialized only when the Singleton Class is used for the first time. Doing so creates the instance of the Singleton class in the JVM Java Virtual Machine during the execution of the method, which gives access to the instance, for the first time.
init
gets called only the first time you invoke MyClass.shared
At that point the instance of MyClass
is saved inside the shared
static constant.
Let's consider this Singleton class
final class Singleton {
static let shared = Singleton()
private init() {
print("Singleton initialized")
}
var count = 0
}
Now let's look at the output into the console
As you can see the Singleton initialized
string is printed only once. This means the init is only called once.
Note: Of course I assumed the implementation of your Singleton class is correct.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With