Good case for Singletons?

后端 未结 10 1594
臣服心动
臣服心动 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:56

    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 accross the entire application and it has some state, it makes sense to make it a singleton

    In your case, the settings of the application is a good candidate for singleton.

    On the other hand, a class can only have static methods if you want to group certain functions together, such as utility classes, examples in jdk are java.util.Arrays java.util.Collections. These have several related methods that act on arrays or collections

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2021-01-05 08:01

    Since your class is holding global settings, a pro for a singleton could be that you have more control about creation of the singleton. You could read a configuration file during object creation.

    In other cases if methods are static there would be no benefit like in javas Math class which has only static members.

    A more obvious need for singletons is when you implement factories as singletons, because you can interchange different implementations of this factory.

    0 讨论(0)
  • 2021-01-05 08:04

    I consider the Singleton pattern to be the most inappropriately applied design pattern. In ~12 years of software development I'd say I've maybe seen 5 examples that were appropriate.

    I worked on a project where we had a system monitoring service that modeled our system with a System class (not to be confused with Java's built-in System class) that contained a list of Subsystems each with a list of Components and so on. The designer made System a Singleton. I asked "Why is this a Singleton?" Answer: "Well, there is only one system." "I know, but, why did you make it a Singleton? Couldn't you just instantiate one instance of a normal class and pass it to the classes that need it?" "It was easier to just call getInstance() everywhere instead of passing it around." "Oh..."

    This example is typical: Singletons are often misused as a convenient way to access a single instance of a class, rather than to enforce a unique instance for technical reasons. But this comes at a cost. When a class depends on getInstance(), it is forever bound to the Singleton implementation. This makes it less testable, reusable, and configurable. It violates a basic rule I follow and that probably has a common name in some design principles essay somewhere: classes should not know how to instantiate their dependencies. Why? Because it hardcodes classes together. When a class calls a constructor, it is bound to an implementation. getInstance() is no different. The better alternative is to pass an interface into the class, and something else can do the constructor/getInstance()/factory call. This is where dependency injection frameworks like Spring come in, though they are not necessary (just really nice to have).

    So when is it appropriate to use a Singleton? In that rare case where instantiating more than one of something would literally ruin the application. I'm not talking about instantiating two Earths in a solar system app - that's just a bug. I mean where there is some underlying hardware or software resource that will blow up your app if you call/allocate/instantiate it more than once. Even in this case, classes that use the Singleton should not know it is a Singleton. There should be one and only one call to getInstance() that returns an interface that is then passed to constructors/setters of classes that need it. I guess another way of saying it is that you should use a Singleton for its "singleness" and not for its "globally accessibleness".

    By the way, on that project I mentioned where System was a Singleton... Well System.getInstance() was laced throughout the code base, along with several other inappropriate Singletons. A year later some new requirements came down: "We are deploying our system to multiple sites and want the system monitoring service to be able to monitor each instance." Each instance... hmmm... getInstance() ain't gonna cut it :-)

    0 讨论(0)
提交回复
热议问题