c# - Singleton Factory to produces multiple singleton instances -


i have 2 singleton classes in project.

public class vstatemanager : ivstate {     private static readonly object _createlock = new object();     private static vstatemanager _vsmanager = null;     public static vstatemanager getvstatemanager()     {         lock (_createlock)         {             if (_vsmanager == null)             {                 return new vstatemanager();             }             return _vsmanager;         }     } }  public class vtrfactory : ivtr {     private static vehiclefactory _vtrfactory =null;     private static readonly object _createlock = new object();      public static vehiclefactory getvtrfactory()     {         lock(_createlock)         {             if(_vtrfactory == null)             {                 return new vtrfactory();             }             return _vtrfactory;         }     } } 

my colleague suggested create singleton class (something singleton factory) accepts generic interface , produces both these singleton objects

how can done.?

first of all, classes aren't implementing singleton @ all. @ this:

if (_vsmanager == null) {    return new vstatemanager(); } return _vsmanager; 

_vsmanager null, multiple instances created each time access instance. should be:

if (_vsmanager == null) {    _vsmanager = new vstatemanager(); } return _vsmanager; 

that's way ensure 1 instance created.

also, use property instead of function, it's more clear:

public class vstatemanager : ivstate {     private static readonly object _createlock = new object();     private static vstatemanager _vsmanager = null;     public static vstatemanager instance     {                 {             lock (_createlock)             {                 if (_vsmanager == null)                 {                     _vsmanager = new vstatemanager();                 }                 return _vsmanager;             }         }     } } 

then can use per example vstatemanager.instance.xxx.

second, why need third class create singletons? when need use them accessing getxxxx create needed instance, there reason create instances before need them?

if need instances initialized before needed can simple this:

public static class initializer() {     public static void init()     {         var = vstatemanager.getvstatemanager();         var b = vehiclefactory.getvtrfactory();     } } 

then initialize call initializer.init(). overcomplicating code without reason root of evil in programming, don't try solve problem doesn't exists solution can create real problems.


Comments

Popular posts from this blog

resizing Telegram inline keyboard -

command line - How can a Python program background itself? -

php - "cURL error 28: Resolving timed out" on Wordpress on Azure App Service on Linux -