0
0
LLDsystem_design~10 mins

Singleton pattern in LLD - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to declare the private static instance variable in the Singleton class.

LLD
private static [1] instance;
Drag options to blanks, or click blank then click option'
ASingleton
Bvoid
Cint
Dpublic
Attempts:
3 left
💡 Hint
Common Mistakes
Using a primitive type instead of the class type.
Declaring the instance as public instead of private.
2fill in blank
medium

Complete the code to make the constructor private in the Singleton class.

LLD
[1] Singleton() { }
Drag options to blanks, or click blank then click option'
Apublic
Bprivate
Cprotected
Dstatic
Attempts:
3 left
💡 Hint
Common Mistakes
Making the constructor public or protected.
Making the constructor static, which is not allowed.
3fill in blank
hard

Fix the error in the getInstance method to correctly return the Singleton instance.

LLD
public static Singleton getInstance() {
    if (instance == null) {
        instance = new Singleton();
    }
    return [1];
}
Drag options to blanks, or click blank then click option'
ASingleton
Bthis
Cinstance
Dnew Singleton()
Attempts:
3 left
💡 Hint
Common Mistakes
Returning 'this' inside a static method.
Returning a new Singleton object every call.
4fill in blank
hard

Fill both blanks to implement thread-safe lazy initialization using synchronized block.

LLD
public static Singleton getInstance() {
    if (instance == null) {
        synchronized([1]) {
            if (instance == null) {
                instance = new [2]();
            }
        }
    }
    return instance;
}
Drag options to blanks, or click blank then click option'
ASingleton.class
Bthis
CSingleton
Dinstance
Attempts:
3 left
💡 Hint
Common Mistakes
Synchronizing on 'this' inside a static method.
Using the instance variable as the lock object.
5fill in blank
hard

Fill all three blanks to implement the Singleton pattern with eager initialization.

LLD
public class Singleton {
    private static final [1] instance = new [2]();

    [3] Singleton() { }

    public static [1] getInstance() {
        return instance;
    }
}
Drag options to blanks, or click blank then click option'
ASingleton
Bpublic
Dprivate
Attempts:
3 left
💡 Hint
Common Mistakes
Making the constructor public.
Not using static final for the instance variable.