Good case for Singletons?

后端 未结 10 1683
臣服心动
臣服心动 2021-01-05 07:24

I have an application that has several classes used for storing application-wide settings (locations of resources, user settings, and such). Right now these classes are just

10条回答
  •  我在风中等你
    2021-01-05 07:45

    Effective Java says:

    Singletons typically represent some system component that is intrinsically unique, such as a video display or file system.

    So if your component warrants single instance across the entire application and it has some state, it makes sense to make it a singleton.

    (The above nakedly borrowed from naikus)

    In many cases the above situation can be handled by a 'utility class' in which all the methods are static. But sometimes a Singleton is still preferred.

    The main reason for advocating a Singleton over a Static Utility Class is when there is a non-negligible cost involved in setting it up. For example if your class represents the file system, it will take some initialization, which can be put in the constructor of a Singleton but for a Static Utility Class will have to be called in the Static Initializer. If some executions of your app might never access the file system then with a Static Utility Class you have still paid the cost of initializing it , even though you don't need it. With a Singleton if you never need to instantiate it you never call the initialization code.

    Having said all that, Singleton is almost certainly the most-overused design pattern.

提交回复
热议问题