Good case for singleton?

I have an application in which there are several classes used to store application settings (location of resources, user settings, etc.). Now these classes are just full of static fields and methods, but I never created them.

Someone suggested that I make them singleton, what is the case / against?

+7
java static singleton
source share
10 answers

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 guarantees one instance throughout the application and has some state , it makes sense to make it singleton

In your case, application settings are a good candidate for singleton.

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

+8
source share

I consider the Singleton pattern to be the most unmanaged design pattern. For ~ 12 years of software development, I would say that I might have seen 5 examples that would be suitable.

I was working on a project in which we had a system monitoring service that simulated our system with the System class (not to be confused with the Java-built System class), which contained a list of Subsystem , each of which is a list of Component , etc. Designer made System singleton. I asked: "Why is this Singleton?" Answer: "Well, there is only one system." "I know, but why did you do this with Singleton? Could you just create an instance of a regular class and pass it to the classes that need it?" "It was easier to just call getInstance() everywhere and not pass it." "ABOUT..."

This example is typical: singletones are often misused as a convenient way to access a single instance of a class, rather than forcing a unique instance for technical reasons. But it is expensive. When a class depends on getInstance() , it is always bound to a Singleton implementation. This makes it less verifiable, reusable and customizable. This violates the basic rule that I follow, and which probably has a common name in some draft essay on principles: classes do not need to know how to create their dependencies. What for? Because it hardcodes classes together. When a class calls the constructor, it is associated with the implementation. getInstance() is no different. A better alternative is to pass the interface to the class, and something else might cause the constructor to call / getInstance() / factory. This is where dependency frameworks such as Spring come in, although they are not needed (just really nice to have).

So, when is it appropriate to use Singleton? In the rare case when creating an instance of more than one of them would literally spoil the application. I'm not talking about creating two Earths in a solar system application - it's just a mistake. I mean, where are some basic hardware or software resources that will blow up your application if you call / allocate / create it several times. Even so, classes using Singleton need not know that they are Singleton. There should be one and only one call to getInstance() , which returns an interface, which is then passed to the constructors / setters of the classes that need it. I suppose another way of saying that you should use Singleton is for your "uniqueness" and not for your "global availability."

By the way, in this project I mentioned where System was Singleton ... Well System.getInstance() was laced throughout the code base along with several other inappropriate singletones. A year later, some new requirements appeared: "We are deploying our system on several sites and we want the system monitoring service to be able to track each instance." Each instance ... hmmm ... getInstance() not going to cut it :-)
+10
source share

Singleton will provide you with a link to an object that you can use throughout your application ... you will use singleton if you want objects and / or polymorphism ...

+1
source share

If you do not need to create them, I do not see the point in single games. Well, I have to fix it - if these classes cannot be created, then it makes no sense to compare them with single points - a singleton template restricts an instance to a single object, and comparison with what cannot be created does not make sense.

I find that my main use for singleons usually involves a class that has static methods that, perhaps after preparing the environment, instantiate themselves. Using private constructors and overriding Object.clone() to throw a CloneNotSupportedException , no other classes can create a new instance, or if they ever passed an instance of it, they cannot clone it.

I think I would say that if your application settings are part of a class that is never created, it doesn't matter to say "It should / should not be single."

0
source share

I think you do not need to create a signleton class. just make this class constructor private. Like a Math class in java.

 public final class Math { /** * Don't let anyone instantiate this class. */ private Math() {} //static fields and methods } 
0
source share

Singlets often appear in situations similar to the description: you have some kind of global data that should live in some place, and you only need one, it is advisable that you be sure that you can do one.

The simplest thing you can do is a static variable:

 public class Globals{ public static final int ACONSTANT=1; 

This is great and ensures that you only have one and you have no problem creating. The main drawback, of course, is that it is often inconvenient to process your data. It also encounters a load problem if, for example, your line is actually built, for example, by creating something from an external resource (there is also getcha with primitives there - if your static final is int, let's say classes that depend on it , compile it inline, which means that recompiling your constants may not replace the constants in the application - for example, when setting public class B{ int i = Globals.ACONSTANT; } changing Globals.ACONSTANT and recompiling only Globals will leave Bi still = 1.)

Building your own singleton is the next simplest thing, and it is often beautiful (although you can find discussions of the problems inherent in single-user downloads, such as double-checked locks ). Such problems are a big reason why many applications are created using Spring, Guice, or some other structure that controls resource loading.

So basically: Statics

  • Good: easy to code, code clear and simple
  • bad: not configurable - you need to recompile to change your values, it may be inoperable if your global data requires complex initialization

Singletones fix some of them, dependency frameworks fix and simplify some problems associated with loading single-user mode.

0
source share

Since your class supports global settings, pro for singleton may be that you have more control over creating a singleton. You can read the configuration file while creating the object.

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

A more obvious need for singleons is that you implement factories as single, because you can exchange different implementations of this factory.

0
source share

Sometimes, what people think of as Singleton objects can really be private members of the class. In other cases, they must be unique global variables. Depending on what design they need.

If there should be one and exactly one instance of the object: use Singleton. By this I mean if the program needs HALT, if there is more than one object. A good example is that you are developing a video game that supports rendering only one output device. Trying to open the same device again (ashamed of you for hard coding!) Would be prohibited. IMHO this case often means that you should not use classes in the first place. Even C allows you to trivially encapsulate such a problem without the complexity of creating a Singleton class and still support OO elements that apply to singleton. When you're stuck in a language such as Java / C #, a singleton pattern is what you need to work with, unless purely static members do the trick themselves. You can still imitate another way.

If this is just a case of pairing objects, you should probably think more than object-oriented. Here's another example: let our game engine rendering codes have to interact with resources and input managers so that it can do the job. You can make these singletones and do it like ResourceManager.getInstance (). GetResource (name). Or you can create an application class (e.g. GameEngine) that has a ResourceManager and InputManager as private members. Then let GameEngine pass them as needed to the rendering code methods. For example, r.render (resourcemanager);

For singletones, you can easily access it from anywhere, it's like a global variable, but there can only be one copy of it.

Against annual multi-user systems, you can solve it by encapsulating it inside the parent object and passing the member object to other methods of member objects.

Sometimes just using a stupid global variable is the right thing. Similar to using GOTO or complex (and / or) conditional instructions instead of writing the same error handling code N times with copy and paste.


The code is smarter, not harder.

0
source share

You must use singletones to modulate.

Imagine the following objects in singleton:

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

Case 1 Imagine if you didn’t do this, but one class for storing all static fields / methods. Then you will have one large pool that you have to deal with.

Case 2
In your current case, you divided them into appropriate classes, but as static links. Then there will be too much noise, because each static property is now available to you. If you do not need information, especially when there is a lot of static information, you should limit the current scope of the code to the lack of information.

Preventing data clutter helps in maintenance and ensures that dependencies are limited. Somehow, having an idea of ​​what is or is not available to me, in my current area of ​​coding, helps me coding more efficiently.

Case 3 Resource Identifier.
Singletones make it easy to scale resources. Let's say you now have a single database, and so you set all its parameters as static in the MyConnection class. What if the time has come when you need to connect to multiple databases? If you encoded the connection information as a singleton code, raising the code would be relatively simple.

Case 4 Inheritance.
Single classes allow you to roll over. If you have a resource class, they can share common code. Say you have a BasicPrinter class that can be used as a singleton. Then you have LaserPrinter, which extends BasicPrinter.

If you used static tools, your code will break because you cannot access BasicPrinter.isAlive like LaserPrinter.isAlive. Then your single piece of code will not be able to manage different types of printers unless you place redundant code.

If you code in Java, you can still create a fully static content class and use the instance reference to access its static properties. If someone should do it, why not just make it a single?

Of course, extending Singleton classes has its own problems beyond this discussion, but there are simple ways to mitigate these problems.

Case 5 Avoid Information. There are so few pieces of information that need to be made globally available, like the largest and smallest integers. Why is Printer.isAlive allowed to make a stand? Only a very limited set of information should be admitted to the rostrum.

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

0
source share

Effective Java says:

Singlets are usually a system component that is inherently unique, such as a video display or file system.

So, if your component guarantees a single instance throughout the application and has some kind of state, it makes sense to make it single.

(The above is arrogantly taken from naikus)

In many cases, the above situation can be handled by a “utility class” in which all methods are static. But sometimes Singleton still prefers.

The main reason for protecting Singleton over the static utility class is when there is a minor cost associated with setting it up. For example, if your class represents a file system, you will need initialization, which can be placed in the Singleton constructor, but for the Static Utility Class, you will have to call it in the static initializer. If some executions of your application can never access the file system, then using the Static Utility Class you will still pay to initialize it, even if you do not need it. With Singleton, if you don't need to instantiate, you never call the initialization code.

Having said all this, Singleton is almost certainly the most confusing design pattern.

0
source share

All Articles