Singleton or class and static members?

I was researching some projects in .NET and Java and from what I understood the benefits of Singleton, I found it unnecessary to use it. for example: in a project it was used to instantiate classes that loaded data into memory when the program was started. In this case, why not call a static method where you load all this data into memory?

What are the advantages of using do you designate pattern Singleton ?

I can't think of any example where it's not possible to replace any Singleton implementation with a simple use of static members.

Author: gmsantos, 2014-07-14

5 answers

Undoing a mess

In one project The [Singleton pattern] was used to instantiate classes that loaded data into memory when the program was started.

In fact, Singleton does not serve to start data at the start of the program, but rather to ensure a single instance (within a context) of a certain object.

Then, it does not matter if the object is instantiated at the start of the program ( eager) or at the first called to the method (lazy ).

Two implementations

public class Singleton {

    private static Singleton eagerInstance = new Singleton();
    public static Singleton getEagerInstance() {
        return eagerInstance;
    }

    private static Singleton lazyInstance;
    public static Singleton getLazyInstance() {
        if (lazyInstance == null) {
            synchronized (Singleton.class) {
                if (lazyInstance == null) {
                    lazyInstance = new Singleton();
                }
            }
        }
        return lazyInstance;
    }

}

Instantiating the object at the start of the program (or loading the class) is simpler, because we don't have to worry about synchronization. However, the resources used are allocated even if they are not used.

Leaves to instantiate the object on demand saves resources in some cases, but may cause a certain delay in responding to the first client that uses the resource and requires extra care with competition. Yes, both if s are required to ensure 100% that there is no chance of loading the object twice on a concurrent call.

To Singleton or not to Singleton?

Now think of the example eager and the following comment:

Why not call a static method where you load all this data into memory?

Loading the data into memory via a static method is pretty much what I did in the example above. So, at the end of the day, your implementation is still a Singleton.

On the other hand, if you access instances directly by an attribute, for example Singleton.instance, then it really isn't about the Singleton pattern.

And this brings several disadvantages, which go beyond the disadvantages of the Singleton pattern itself, such as the encapsulation break and the high coupling between implementations.

Considerations

Ultimately, every design pattern is dispensable.

Anyone who has read the GoF carefully must have realized that the most cited side effect in the standards is the increase in complexity and the number of classes.

The truth is that there are much more direct ways to solve problems. The big difference between not using patterns and using them (properly) can be observed in the long run.

Solving a problem more simply and directly can cause an even bigger problem from a maintenance point of view. By example, using a static attribute as I mentioned above can cause serious problems if the way the system works changes. Imagine if tomorrow it is no longer a Singleton, but needs to be a ThreadLocal (Singleton per thread). Serious errors can also emerge after load, performance, and concurrency tests that require synchronization of the recovered object.

Finally, let's consider the last statement:

I can't think of any examples where it's not possible replace any Singleton implementation with a simple use of static members.

In general, this is because there is no difference. The Singleton pattern is just a formalization of how to properly access a static attribute.

 14
Author: utluiz, 2014-07-14 14:54:06

The application for it are several, What You mentioned is another example of implementation, however the real goal of having a singleton is to ensure that it will only be instantiated once, here is a practical example:

Imagine the following situation, the mouse pointer is a class of type singleton and can only be instantiated once.

 3
Author: Diego Vieira, 2014-07-14 13:17:59

Gustavo Piucco, the singleton project pattern exists to ensure that a given class will be instantiated only once. It is commonly used with a facade, to ensure that an application developed In N layers has only one entry point. Below is a practical example of it. In this example, we have a facade class that directly accesses your business classes. To ensure that there is no more than one instance accessing these business classes, the singleton.

public class Fachada
{
    private Fachada instancia;  

    private Fachada()
    {
    }

    public static Fachada GetFachada()
    {
        if(instancia == null)
            instancia = new Fachada();
        return instancia;
    }   

    //Métodos de acesso a classe de negócio

}

Unlike a static class, singleton allows you to have non-static methods and objects.

 3
Author: Vinícius, 2014-07-14 13:41:30

Using Singleton unlike of a static class, its class depending on the scenario can:

  • inherit from another class
  • be inherited;
  • implement an interface;
  • be serialized;
  • be passed to other classes;
  • be tested more easily;

Using the static class would have only static methods.

 3
Author: Renan, 2014-07-14 15:47:40

The advantage of using Singleton is that the code accessing Singleton does not know how it was implemented. See the singleton example below, in Java:

public class MySingleton {
      // Variavel estática que conterá a instancia do método
      private static MySingleton INSTANCE = new MySingleton();

     static {
              // Operações de inicialização da classe
     }

     // Construtor privado. Suprime o construtor público padrao.
     private MySingleton() {
     }

     // Método público estático de acesso único ao objeto!
     public static MySingleton getInstance(){

           // O valor é retornado para quem está pedindo
           return INSTANCE;
     }
 }

The Code that calls Singleton simply executes: MySingleton.getInstance();, not knowing if the same is a static instance or if an object is created every time that this call is made. The interesting thing about this approach is that the client, that is, who calls Singleton, is not interested in knowing the implementation of Singleton, that is, the service he calls.

The advantage of using Singleton is the organization of the code, using encapsulation. Notice that using simply static method calls, such good practice is not applied.

A classic example is the case of log, where you want only one instance in the entire application generating log, since the same is done in only one file.

See the wikipedia link with Sigleton's explanations.

 2
Author: EduardoFernandes, 2014-07-14 14:48:16