C# Concepts 3
C# Concepts 3
• Definition: The Singleton pattern ensures that a class has only one
instance and provides a global point of access to that instance.
Singleton Pattern : Characteristics
• Controlled Instance Creation: Only one instance exists throughout
the application's lifecycle.
// Usage
class Program
{
static void Main(string[] args)
{
Singleton.Instance.DoWork();
}
}
Singleton Pattern - Example
Simple Factory Pattern - Advantages
• Controlled Access: Only one instance is created, ensuring
consistency.
Instantiation One instance controlled by the class itself One instance controlled by the class itself
State Can maintain state through instance
Can maintain state through instance fields
Management fields
Inheritance Can implement interfaces and be Can implement interfaces and be inherited
inherited from from
Testability More testable via interfaces and mocking More testable via interfaces and mocking
Lazy Initialization Supports lazy initialization Supports lazy initialization
Usage Scenario When a single instance with state is
When a single instance with state is needed
needed
Choosing Between Singleton and
Static:
• Use Singleton:
• When you need a single instance that maintains state.
• When you need to implement interfaces or inherit from other classes.
• When you require lazy initialization.
• Use Static:
• For stateless utility or helper functions.
• When no instance-specific behavior is needed.
• When simplicity and performance are priorities.