Good case for Singletons?

后端 未结 10 1597
臣服心动
臣服心动 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条回答
  •  -上瘾入骨i
    2021-01-05 07:58

    You should use singletons for modularization.

    Imagine the following entities in singleton:

    Printer prt;
    HTTPInfo httpInfo;
    PageConfig pgCfg;
    ConnectionPool cxPool;
    

    Case 1. Imagine if you did not do that, but a single class to hold all the static fields/methods. Then you would have one big pool of static to deal with.

    Case 2.
    In your current case, you did segregate them into their appropriate classes but as static references. Then there would be too much noise, because every static property is now available to you. If you do not need the information, especially when there is a lot of static information, then you should restrict a current scope of the code from seeing unneeded information.

    Prevention of data clutter helps in maintenance and ensure dependencies are restricted. Somehow having a sense of what is or is not available to me at my current scope of coding helps me code more effectively.

    Case 3 Resource identity.
    Singletons allow easy up-scaling of resources. Let us say you now have a single database to deal with and therefore, you place all its settings as static in the MyConnection class. What if a time came when you are required to connect to more than one database? If you had coded the connection info as a singleton, the code enhancement would comparative much simpler.

    Case 4 Inheritance.
    Singleton classes allow themselves to be extended. If you had a class of resources, they can share common code. Let's say you have a class BasicPrinter which is instantiable as singleton. Then you have a LaserPrinter which extends BasicPrinter.

    If you had used static means, then your code would break because you would not be able to access BasicPrinter.isAlive as LaserPrinter.isAlive. Then your single piece of code would not be able to manage different types of printers, unless you place redundant code.

    If you are coding in Java, you could still instantiate a totally static content class and use the instance reference to access its static properties. If someone should do that, why not just make that a singleton?

    Of course, extending singleton classes have their issues beyond this discussion but there are simple ways to mitigate those issues.

    Case 5 Avoid information grandstanding. There are so few pieces of info that needs to be made globally available like the largest and smallest integers. Why should Printer.isAlive be allowed to make a grandstand? Only a very restricted set of information should be allowed to make a grandstand.

    There is a saying: Think globally, act locally. Equivalently, a programmer should use singletons to think globally but act locally.

提交回复
热议问题