Some objects should exist only once in a program, like its settings. If every part made its own copy, the parts would not agree. A change made in one part would be missing from the others.
The Singleton pattern solves this. The class makes its one instance itself, the first time someone asks for it. After that, every part gets that same instance from one place.
Here you write Settings, the settings of an app. It stores a value for each key.
Implement the class:
GetSettings()returns a pointer to the one instance. The first call makes it. Every later call returns that same pointer.set(key, value)storesvalueunderkey. It replaces the old value if there was one.get(key)returns the value stored underkey, or "none" whenkeyisn't set.remove(key)removeskey. It returnstrueifkeywas set, andfalseotherwise.count()returns how many keys are set.
Go has no classes. Settings is a struct, and its methods have a pointer receiver. A package variable holds the one instance.
The tests run two parts of an app, ui and server. Neither part keeps a Settings of its own. For every command, the part asks GetSettings() again, then calls one method.
Each line of the input is one command. For example, ui set theme dark means that the ui part calls set("theme", "dark"). A same line checks that two calls of GetSettings() give the very same object.
The app starts with no key set. Each command writes one line, except set, which writes nothing:
getwrites the value, or none.removeandsamewrite True or False.countwrites the number.
Example 1:
Input:
1. ui set theme dark
2. server get theme
3. server set theme light
4. ui get theme
5. ui get volume
6. server count
7. same
8. server remove theme
9. ui remove theme
10. ui count
Output:
dark
light
none
1
True
True
False
0
Explanation:
The ui sets theme to dark.
The server gets the same instance, so it reads dark.
The server changes theme to light, and the ui sees light.
The ui gets none for volume, which was never set.
One key is set.
Both calls of GetSettings() give the same object.
The server removes theme.
Then the ui finds no theme to remove.
Example 2:
Input: 1. server set lang en 2. ui set volume 7 3. ui set lang fr 4. server get lang 5. ui remove font 6. server count 7. server get volume Output: fr False 2 7 Explanation: The ui replaces the lang that the server set. No font was ever set, so there is nothing to remove. Two keys are set, lang and volume.
Constraints:
- Keys and values are words of 1 to 20 characters.
- They use lowercase letters, digits and "-".
- No value is the word "none".
- There are at most 100,000 commands.
- There are at most 50,000 different keys.
Note:
Each method should run in O(1) time on average. Keep the keys and values in a hash map.
Free plan: 30 tutor messages. PRO is unlimited.
