nerdexam
Oracle

1Z0-804 · Question #27

Which two properly implement a Singleton pattern?

The correct answer is A. class Singleton { D. enum Singleton {. A: Here the method for getting the reference to the SingleTon object is correct. B: The constructor should be private C: The constructor should be private Note: Java has several design patterns Singleton Pattern being the most commonly used. Java Singletonpattern belongs to the…

Object-Oriented Design Principles

Question

Which two properly implement a Singleton pattern?

Options

  • Aclass Singleton {
  • Bclass Singleton {
  • Cclass Singleton {
  • Denum Singleton {

How the community answered

(26 responses)
  • A
    73% (19)
  • B
    19% (5)
  • C
    8% (2)

Explanation

A: Here the method for getting the reference to the SingleTon object is correct. B: The constructor should be private C: The constructor should be private Note: Java has several design patterns Singleton Pattern being the most commonly used. Java Singletonpattern belongs to the family of design patterns, that govern the instantiation process. This design patternproposes that at any time there can only be one instance of a singleton (object) created by the JVM. The class's default constructor is made private, which prevents the direct instantiation of the object by others(Other Classes). A static modifier is applied to the instance method that returns the object as it then makes thismethod a class level method that can be accessed without creating an object. OPTION A == SHOW THE LAZY initialization WITHOUT DOUBLE CHECKED LOCKING OPTION D == Serialzation and thraead-safety guaranteed and with couple of line of code enum Singletonpattern is best way to create Singleton in Java 5 world. AND THERE ARE 5 WAY TO CREATE SINGLETON CLASS IN JAVA 1>>LAZY LOADING (initialization) USING SYCHRONIZATION 2>>CLASS LOADING (initialization) USING private static final Singleton instance = new Singleton(); 4>>USING STATIC NESTED CLASS 5>>USING STATIC BLOCK AND MAKE CONSTRUCTOR PRIVATE IN ALL 5 WAY.

Topics

#Singleton pattern#private constructor#enum singleton#static instance

Community Discussion

No community discussion yet for this question.

Full 1Z0-804 Practice