Sobes.tech
Junior — Middle

How can you ensure that an object instance is created only once during program execution?

sobes.tech AI

Answer from AI

To ensure that an object instance is created only once during the execution of a program, the Singleton pattern can be used.

Main verification methods:

  • Singleton Implementation: the class controls the creation of its instance by providing a static method to access it.
  • Testing: you can write a test that calls the object creation multiple times and checks that all references point to the same object.

Example in Java:

public class Singleton {
    private static Singleton instance;

    private Singleton() { }

    public static synchronized Singleton getInstance() {
        if (instance == null) {
            instance = new Singleton();
        }
        return instance;
    }
}

In the test, you can verify:

Singleton s1 = Singleton.getInstance();
Singleton s2 = Singleton.getInstance();
assert s1 == s2; // Check that references point to the same object

Thus, it is confirmed that the object is created only once.

How can you ensure that an object instance is created… - sobes.tech