Categories
java

singleton in java with example

In this post, we will learn singleton in java with example

Singleton is one of the famous design pattern in java. Below are few point of Singleton

  • We Should have the only one instance in the application
  • In below example, we are going to use Lazy Initialization
  • It will create an instance when the application in need
  • We should have a private constructor to avoid outside initialization
public class SingletonExample {

	public static SingletonExample singletonExampleObject = null;

	public String stringVarible = "Singleton string";

	private SingletonExample() {

	}

	public static SingletonExample getSingletonInstance() {
		if (null == singletonExampleObject) {
			singletonExampleObject = new SingletonExample();
		}
		return singletonExampleObject;
	}

}

The above class is an example of Singleton. As mentioned in the above sentence we have a private constructor and static instance of the class

public class Example {

	public static void main(String[] args) {
		try {
			SingletonExample singletonObject = SingletonExample.getSingletonInstance();
			System.out.println(singletonObject.stringVarible);
			singletonObject.stringVarible = "BeginnersBug";

			// Creating another object
			SingletonExample singletonInstance = SingletonExample.getSingletonInstance();
			System.out.println(singletonInstance.stringVarible);
		} catch (Exception e) {
			e.printStackTrace();

		}
	}

}
Singleton string
BeginnersBug

Even though we have two variables for SingletonExample it is sharing same instance

So the Value of stringVaraible is reflected on the second variable

Conclusion

In the above post, we learned about singleton in java with example

Github

https://github.com/rkumar9090/student-example/tree/master/src/main/java/com/beginnersbug/example/singleton

Related Articles

convert java object to JSON string