Alternating Singleton Pattern

medium
design patterns singleton pattern object-oriented design multithreading
🏢microsoft
0 views0 likes

Problem Description

Implement a modified singleton pattern that alternates between two instances. The class should store two instances internally and return the first instance on even calls of getInstance(), and the second instance on odd calls of getInstance().

Constraints:

  • The class should lazily initialize both instances (i.e., create them upon the first request).
  • Assume calls to getInstance() are zero-indexed for the purpose of deciding between even and odd calls.

Example Implementation: (Pseudocode)

class AlternatingSingleton {
    private static instance1: AlternatingSingleton = null;
    private static instance2: AlternatingSingleton = null;
    private static callCount: int = 0;

    private constructor() {
        // Private constructor to prevent external instantiation.
    }

    public static getInstance(): AlternatingSingleton {
        if (this.instance1 == null) {
            this.instance1 = new AlternatingSingleton();
        }
        if (this.instance2 == null) {
            this.instance2 = new AlternatingSingleton();
        }

        this.callCount++;
        if (this.callCount % 2 == 0) {
            return this.instance1;
        } else {
            return this.instance2;
        }
    }
}

Hints

[object Object]

[object Object]

[object Object]