Singleton or class and statics?

Asked

Viewed 1,347 times

17

I was researching some projects in .Net and Java and from what I understand of 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 load all this data in memory?

What are the advantages of using the Pattern designation Singleton?

I cannot think of any example where it is not possible to replace any implementation Singleton by a simple use of static members.

5 answers

14


Cleaning up a mess

in a project [Singleton standard] was used to instantiate classes that loaded data into memory when the program was started.

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

There, it does not matter if the object is instantiated at the beginning of the program (ager) or on the first call 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 beginning of the program (or loading the class) is simpler, because we don’t need to worry about synchronization. However, the resources used are allocated even if they are not used.

It allows to instantiate the object on demand saves resources in some cases, but can cause a certain delay in responding to the first customer who uses the resource and requires extra care with the competition. Yes, both of you ifs are required to ensure 100% that there is no chance to load the object twice in a concurrent call.

To Singleton or not to Singleton?

Now, think of the example ager and the following comment:

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

Loading the data in memory through a static method is practically 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 isn’t about the Singleton standard.

And this brings 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 standard is expendable.

Those who read the Gof carefully should have already noticed that the most cited side effect in the patterns 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. For example, using a static attribute as mentioned above can cause serious problems if the way the system works changes. Imagine if tomorrow he’s no longer a Singleton, but needs to be a ThreadLocal (Singleton per thread). Severe errors may 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 example where it’s 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 standard is just a formalization of how to properly access a static attribute.

  • 2

    Great answer! The last sentence cleared my question. My mistake was to take the Singleton standard as a rule, like "I need to implement it somewhere in my code!".

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 is a practical example:

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

  • But what I can not understand is why not just use as static since it will have only one instance. In my head is the same thing.

  • 2

    No, the static method is to use without an object instance as well as a static class you can use several times the static method/object, a Singleton class nay.

3

Gustavo Piucco, the Singleton design standard exists to ensure that a particular 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, use 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

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

  • Inherit from another class
  • Inherited;
  • Implement an interface;
  • Be serialized;
  • Be passed to other classes;
  • To be tested more easily;

Using the static class would have only static methods.

2

The advantage of using Singleton is that the code that accesses Singleton does not know how to implement it. 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 it is a static instance or if an object is created every moment that this call is made. The interesting thing about this approach is that the customer, 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. Note that using simply static calls of methods, such good practice is not applied.

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

See the wikipedia link with explanations by Sigleton.

  • 1

    The advantage of using Singleton is not that the code that accesses Singleton does not know how to implement it. @Eduardofernandes I think this is encapsulation, an important principle of object orientation, but it is not an "advantage" of using Singleton.

  • You are right :). Thank you

  • Yes, indeed, there is encapsulation with Singleton. However it is possible to encapsulate methods, organize your code, use p/decrease matching resources between objects, etc., without using Singleton.

  • 1

    I agree, but the idea here is to show Singleton’s advantages.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.