🟢 1. Singleton
-
What it is: A class where only one object (instance) is ever created.
-
How you use it: You create and use that single object.
Example:
Key Points
-
You can implement interfaces (e.g.,
ILogger
). -
You can use polymorphism (pass it to methods that expect an interface).
-
Created only when needed (lazy load possible).
-
Lives as long as your app runs, but you control initialization.
🟢 2. Static Class
-
What it is: A class that cannot be instantiated at all.
All members are automatically static. -
How you use it: You call its methods directly, no object needed.
Example:
Key Points
-
No object is ever created.
-
Cannot implement interfaces or inherit from other classes.
-
Loaded automatically when your program starts.
🟢 Side-by-Side Comparison
Feature | Singleton | Static Class |
---|---|---|
Object creation | One object (single instance) | No object |
Interfaces / Inherit | Yes | No |
Polymorphism | Yes | No |
Lazy initialization | Possible | Not applicable |
State/data | Stored inside the single instance | Stored in static fields |
Lifetime | Until app ends or GC collects (if not static) | For whole app domain (always loaded) |
Testing (mocking) | Easy to mock (pass interface) | Hard to mock |
Usage example | Logger.Instance.Log("msg"); | MathHelper.Add(2,3); |
🟢 When to Use
-
Singleton:
When you need one shared object that may hold state or need an interface (e.g., database connection manager, configuration, logging service). -
Static Class:
When you only need utility functions with no state (e.g., math helpers, string helpers).
👉 Quick Rule
-
Need a single shared object? ➜ Singleton
-
Need only static helper methods? ➜ Static class
No comments:
Post a Comment