Singleton Pattern
- Use singleton to ensure a class has a single instance
Classic Structure
Scenario
- Class for managing the configuration settings of application. Store application settings in 1 object
Problem
public class ConfigManager
{
Dictionary<string, object> settings = new Dictionary<string, object>();
public void Set(string key, object value)
{
settings[key] = value;
}
public object Get(string key)
{
return settings[key];
}
}
public class Program
{
static void Main(string[] args)
{
ConfigManager configManager1 = new ConfigManager();
configManager1.Set("name", "gof");
ConfigManager configManager2 = new ConfigManager();
Console.WriteLine(configManager2.Get("name")); //output - null
}
}
- Each object has its own data
- Data should be stored in single object. You can't have multiple objects to store application settings
Solution
public class ConfigManager
{
Dictionary<string, object> settings = new Dictionary<string, object>();
private static ConfigManager instance = new ConfigManager();
private ConfigManager() { }
public static ConfigManager getInstance() { return instance; }
public void Set(string key, object value)
{
settings[key] = value;
}
public object Get(string key)
{
return settings[key];
}
}
public class Program
{
static void Main(string[] args)
{
// Singleton Solution Code
ConfigManager configManager1 = ConfigManager.getInstance();
configManager1.Set("name", "gof");
ConfigManager configManager2 = ConfigManager.getInstance();
Console.WriteLine(configManager2.Get("name"));
}
}
Example Structure
Example Code