Most common examples of misuse of singleton class

后端 未结 11 971
伪装坚强ぢ
伪装坚强ぢ 2020-12-16 00:19

When should you NOT use a singleton class although it might be very tempting to do so? It would be very nice if we had a list of most common instances of \'singletonitis\' t

11条回答
  •  一整个雨季
    2020-12-16 01:02

    Sometimes, you assume there will only be one of a thing, then you turn out to be wrong.

    Example, a database class. You assume you will only ever connect to your app's database.

    // Its our database! We'll never need another
    class Database
    {
    };
    

    But wait! Your boss says, hook up to some other guys database. Say you want to add phpbb to the website and would like to poke its database to integrate some of its functionality. Should we make a new singleton or another instance of database? Most people agree that a new instance of the same class is preferred, there is no code duplication.

    You'd rather have

    Database ourDb;
    Database otherDb;
    

    than copy-past Database and make:

    // Copy-pasted from our home-grown database.
    class OtherGuysDatabase
    {
    };
    

    The slippery slope here is that you might stop thinking about making new instance of classes and instead begin thinking its ok to have one type per every instance.

提交回复
热议问题