Facebook Pixel

Exercise: Singleton

This exercise puts the Singleton pattern into code.

Scenario

An application needs a globally shared ID generator. Multiple callers each obtain a handle via getInstance() and call methods on it. Because they all receive the same object, the counter increments globally — no caller can create a second generator that resets to zero.

Commands

CommandBehaviorOutput
["next", who]Return the next id from the shared generator"<who> got <id>" (ids start at 1 and increase strictly)
["peek"]Return the last id issued without advancing the counter"Last: <id>" (0 if none issued yet)
["reset"]Reset the shared generator's counter to 0"Reset"

Ids are integers starting at 1 and increase across all callers until a reset command. A peek after a reset returns "Last: 0".

Example
Input
7
next Alice
next Bob
peek
next Carol
reset
peek
next Dave
Output
Alice got 1
Bob got 2
Last: 2
Carol got 3
Reset
Last: 0
Dave got 1
Explanation
Alice and Bob each call `next`, incrementing the shared counter to 1 and 2. `peek` reads the counter without advancing it, returning `Last: 2`. Carol calls `next` and gets 3. `reset` zeroes the counter and prints `"Reset"`. A `peek` immediately after reset returns `Last: 0`. Dave's `next` then starts from 1 again, confirming the reset took effect.

Your task

Implement the skeleton in the editor below so the commands produce the output described above.

Invest in Yourself
Your new job is waiting. 83% of people that complete the program get a job offer. Unlock unlimited access to all content and features.
Go Pro