Post

1 Star2 Stars3 Stars4 Stars5 Stars
Loading ... Loading ...

By Rafaela Azevedo
What is: Singleton is a design pattern that restricts the instantiation of a class to one object. The concept is sometimes generalized to systems that operate more efficiently when only one object exists, or that restrict the instantiation to a certain number of objects.
When to use: This is useful when exactly one object is needed to coordinate actions across the system.

How to use in JAVA:
public class SingletonDemo {
private static SingletonDemo instance = null;
private SingletonDemo() { }
public static synchronized SingletonDemo getInstance() {
if (instance == null) {
instance = new SingletonDemo();
}
return instance;
}
}

Or (I prefer this last one, it is more simple and easy to understand):
public class Singleton {
private static final Singleton INSTANCE = new Singleton();

private Singleton() {}

public static Singleton getInstance() {
return INSTANCE;
}
}
This method has a number of advantages:

The instance is not constructed until the class is used.
There is no need to synchronize the getInstance() method, meaning all threads will see the same instance and no (expensive) locking is required.
The final keyword means that the instance cannot be redefined, ensuring that one (and only one) instance ever exists.

This is a very simple explanation, but helped me a lot. If you have some question, just write in the comments.
See you in the next post !

Source: http://azevedorafaela.wordpress.com/2014/04/24/singleton/

Category: Programming, QA, Test and Automation Stuffs, how to use singleton in java, singleton description, what is singleton

Você também pode querer ler

Sem categoria

15 agosto 2017

Singleton

1 Star2 Stars3 Stars4 Stars5 Stars
Loading ... Loading ...
Sem categoria

08 maio 2017

Singleton

1 Star2 Stars3 Stars4 Stars5 Stars
Loading ... Loading ...
Sem categoria

28 abril 2017

Singleton

1 Star2 Stars3 Stars4 Stars5 Stars
Loading ... Loading ...
Sem categoria

10 abril 2017

Singleton

1 Star2 Stars3 Stars4 Stars5 Stars
Loading ... Loading ...

Comments are off for this post.