Purpose of singletons in programming

后端 未结 9 1705
傲寒
傲寒 2020-12-08 01:49

This is admittedly a rather loose question. My current understanding of singletons is that they are a class that you set up in such a way that only one instance is ever crea

9条回答
  •  青春惊慌失措
    2020-12-08 02:20

    The main advantage of a singleton over a class consisting of statics is that you can later easily decide that you need in fact more than one instance, e.g. one per thread.

    However, in practice the main purpose of singletons is to make people feel less bad about having global variables.

    A practical example for a good use of a singleton: you have an app that uses an SQL database and you need a connection pool. The purpose of such a pool is to reuse DB connection, so you definitely want all clients to use the same pool. Thus, having it as a singleton is the correct design. But one day you need the app to connect to a second DB server, and realize that you cannot have connections to different servers in the same pool. Thus your "one instance overall" singleton becomes "one instance per DB server".

提交回复
热议问题