Java Singleton class
Singleton is one of the design pattern under the creation pattern category.
(There are three type of design patterns :
1. Creational patterns
2. Structural patterns
3. Behavioral patterns
)
Below find the sample singleton class :
When you create the singleton class the following points are important.
1. Define the attribute with private and static modifier. (Line no : 3)
2. Create the private constructor (Line no : 12)
3. Create the instance when the instance is null. (Line no : 17)
(There are three type of design patterns :
1. Creational patterns
2. Structural patterns
3. Behavioral patterns
)
Below find the sample singleton class :
When you create the singleton class the following points are important.
1. Define the attribute with private and static modifier. (Line no : 3)
2. Create the private constructor (Line no : 12)
3. Create the instance when the instance is null. (Line no : 17)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | package com.findanidea.singleton; import java.util.logging.Logger; public class SimpleSingleton { private static Logger LOG = Logger.getLogger("SimpleSingleton"); private static SimpleSingleton simpleSingleton; // Enforce Singleton private SimpleSingleton() { // Singleton } public static SimpleSingleton getSingletonInstance(){ if (simpleSingleton == null) { simpleSingleton = new SimpleSingleton(); LOG.info("Simple Singleton instace created...."); } return simpleSingleton; } } |
Is the above singleton class is thread safe ?
Just think.....