Java - Singleton Pattern

in #java6 years ago

What is a pattern?


A pattern represents a design pattern. It is a concrete suggestion of how a problem can be posed. Patterns have hand and foot. With them is possible to learn a good design from professionals.

The singleton pattern


The Singleton Pattern is great for working with objects, but not at a later date. At the beginning we start with the thread unsafe method. As long as you do not work with threads. Another time, when I know that the singleton thread can make sure and what we need to do. Even then go.

How does the singleton pattern work?


We want to be sure that no object can be created by the programmer / user. To achieve this goal, the constructor is simply set to private.

private.png

The arguments of the constructor need not be empty. Now, of course, the question is how to create the first instance. This requires a public static method, which always returns the same instance.

private.png

You will have noticed that this method refers to the instance attribute. Instance is a private static attribute of the singleton itself and is implemented as follows:

private.png

The complete class looks like this:

private.png

Now you should be able to do everything you want with this class.