Singleton and Static

Vikas Kore
3 min readNov 6, 2019

We all know about what is singleton. In this blog I am just focusing on misunderstanding, struct and class singleton limitations and difference.

Singleton

What we know is:
Singleton means only one instance. The singleton pattern guarantees that only one instance of a class is instantiated.

Using single instance we can access properties and functions of a Singleton class and Struct.

FileManager, UIApplication, UIAccelerometer, NotificationCenter, UserDefaults, SKPaymentQueue, UIScreen.main, UIDevice.current, Bundle.main etc, have shared or default properties that are singletons.

What’s the difference between Struct based and Class based singletons?

Singleton Class

Singleton Structure

If you see carefully difference between above two singleton is in declaring shared variable with var and let, because main difference is that class-based mutable singleton works, while struct-based mutable “singleton” doesn’t. Unless you want to make your singleton immutable (which is rare) you should stick to the class-based one.

Static

Static variables have a property of preserving their value.
Static function is a member function of a class that can be called even when an object of the class is not initialized. A static function cannot access any variable of its class except for static variables.

What’s the difference between static class and singleton pattern?
both should be implemented to be thread-safe but limitation of singleton class properties is Global access, its depend upon developer that when to use singleton and not.

Static Class:-

  1. You cannot create the instance of static class.
  2. Loaded automatically by the .NET Framework common language runtime (CLR) when the program or namespace containing the class is loaded.
  3. Static Class cannot have constructor.
  4. We cannot pass the static class to method.
  5. We cannot inherit Static class to another Static class in C#.
  6. A class having all static methods.
  7. Better performance (static methods are bonded on compile time)
  8. Static objects are stored in stack.

Singleton:-

  1. You can create one instance of the object and reuse it.
  2. Singleton instance is created for the first time when the user requested.
  3. Singleton class can have constructor.
  4. You can create the object of singleton class and pass it to method.
  5. Singleton class does not say any restriction of Inheritance.
  6. We can dispose the objects of a singleton class but not of static class.
  7. Methods can be overridden.
  8. Can be lazy loaded when need (static classes are always loaded).
  9. We can implement interface(static class can not implement interface).
  10. Singleton objects are stored in Heap
  11. Singleton classes follow the OOP

Thank you.

--

--