Singleton:
Private constructor
At any time, only 0 or 1 instance of the Singleton class exists in the application
Singleton classes are created without parameters
Assume lazy instantiation as the defult
A single, private, parameterless contructor
sealed
A private static field holds the only reference to the instance
A public static method provides access to this field
public sealed class Singleton
{
private static Singleton? _instance;
private staic readonly object padlock = new object();
public static Singleton Instance
{
get
{
Logger.Log("Instance called.");
lock(padlock)
{
if(_instance == null)
{
_instance = new Singleton();
}
return _instance;
}
}
}
Locking adds thread safety
Initial approach imposes lock on every access, not just first time
Subsequent version is better, but has some issues with the EMCA CLI spec that may be a concern
csharpindepth.com/articles/singleton
Leveraging static constructors:
C# static constructors only run once per appdomain
Are called when any static member of a type is referenced
Make sure you use an expicit static constructor to avoid issue with c# compiler and beforefieldinit
Thread-safe
No locks=>good performance
Complex and non-intuitive (in nested case)
Singleton:
Can implement interfaces
Can be passed as n argument
Can be assigned to variables
Support polymorphism
Can have state
Can be serialized
Static Class:
No interfaces
Cannot be passed as arguments
Cannot be assigned
Purely procedural
Can only access global state
No support for serialization
singleton Behavior Using Containers:
.NET core has built-in support for IOC/DI Containers
Classes request dependencies via constructor
Classes should follow Explicit Dependencies Principle
Container manages abstract-implementation mapping
Container manages instance lifetime
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.