Singleton or class and static members?

16

I was researching some projects in .Net and Java and from what I understood about 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 the designe pattern Singleton ?

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

    
asked by anonymous 14.07.2014 / 14:54

5 answers

13

Undoing a mess

  

In a project, the [Singleton pattern] was used to instantiate classes that were loading data into memory when the program was started.

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

It does not matter if the object is instantiated at the beginning of the program ( eager ) or at the first call to the lazy method.

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 beginning of the program (or loading the class) is simpler because we do not have to worry about synchronization. However, the resources used are allocated even if they are not used.

Lets you instantiate the object on demand saves resources in some cases, but may cause a delay in responding to the first client using the feature and requires extra care with the competition. Yes, the two 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 eager example and the following comment:

  

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

Loading the data into memory using 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 the instances directly by an attribute, for example Singleton.instance , then it really is not the Singleton pattern.

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

Considerations

Ultimately, every design pattern is expendable.

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

The truth is that there are much more direct ways of solving 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 greater maintenance problem. For example, using a static attribute as I mentioned above can cause serious problems if the way the system works changes. Imagine if it's no longer a Singleton tomorrow, but it needs to be ThreadLocal (Singleton per thread). Serious errors can also emerge after load, performance, and concurrency tests that require synchronization of the retrieved object.

Finally, let's consider the last statement:

  

I can not think of any examples where it is not possible to 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.07.2014 / 16:32
3

The application for it is 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's an example practical:

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

    
14.07.2014 / 15:17
3

Gustavo Piucco, the singleton design 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. The following is a practical example of this. 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 is used.

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, the singleton allows you to have non-static methods and objects.

    
14.07.2014 / 15:32
2

The advantage of using Singleton is that the code that accesses Singleton does not know how it was implemented. See the example of the singleton 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 it is a static instance or if an object is created every time that call is made. What's interesting about this approach is that the client, that is, the one who calls Singleton, is not interested in knowing the implementation of Singleton, or the service it calls.

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

A classic example is the case of logging, where you want only one instance of the entire logging application, since it is done in just one file.

See the wikipedia link with explanations of Sigleton.

    
14.07.2014 / 15:11
2

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

  • Inherit from another class
  • Be inherited;
  • Implement an interface;
  • Being serialized;
  • Be passed to other classes;
  • Be tested more easily;

Using the static class would only have static methods.

    
14.07.2014 / 17:16