ابدأ بالتواصل مع الأشخاص وتبادل معارفك المهنية

أنشئ حسابًا أو سجّل الدخول للانضمام إلى مجتمعك المهني.

متابعة

How many ways we can write Singleton Class in Java?

user-image
تم إضافة السؤال من قبل Mohd shahnawaz khan , Associate Project , Cognizant Technology Solution
تاريخ النشر: 2014/04/23
Maria Thomas
من قبل Maria Thomas , Tech Lead , J P Morgan Chase

There are four known ways to write Singleton class in Java.

1. The classic often used one : Create a private constructor and call this inside getInstance() method which is then invoked by the calling class. This should be synchronized using double checked locking. This comes in lazy initialization since the instance is created only when the method is first called.

2. Create a public static final field for the Singleton instance and call the constructor. This is created during class loading. This comes under early initialization.

public static SingletonInstance instance = new SingletonInstance();

3. Using Enums

Eg: public enum Singleton{ INSTANCE }

4. Creating static inner class wherein creation of the instance is done. This is called Singleton Helper model.

Eg:

public class SingletonInstance{

      private SingletonInstance(){}

      private static class SingletonHelper{

          private static final SingletonInstance instance = new SingletonInstance();

      }      

      public SingletonInstance getInstance(){

         return SingletonHelper.instance;

      }

}

المزيد من الأسئلة المماثلة

هل تحتاج لمساعدة في كتابة سيرة ذاتية تحتوي على الكلمات الدلالية التي يبحث عنها أصحاب العمل؟