easy +8 pts

Singleton Factory

Design a factory that returns the same instance for a given key

Create a class `SingletonFactory` that manages singleton instances. The class should have: - An `__init__` method that initializes an empty internal dictionary. - A method `get_instance(self, key, *args, **kwargs)` that: - If `key` already exists in the internal dictionary, returns the existing instance without calling the constructor. - Otherwise, creates a new instance of the class `key` (which is a class object, e.g., `str`, `list`, or a custom class), passing `*args` and `**kwargs` to its constructor, stores it in the dictionary, and returns it. - A method `instance_count(self)` that returns the number of distinct keys stored. The factory should ensure that for the same key, the same instance is returned every time. Implement the `SingletonFactory` class with the specified methods. The tests will instantiate the factory and use helper functions to verify behavior.

Constraints

The key can be any class (or any hashable object, but typically a class). The constructor of the key class can accept any arguments. The internal dictionary should not be exposed directly.

Example

>>> class Counter:
...     def __init__(self, start=0):
...         self.value = start
...     def increment(self):
...         self.value += 1
>>> f = SingletonFactory()
>>> c1 = f.get_instance(Counter, 10)
>>> c2 = f.get_instance(Counter)
>>> c1 is c2
True
>>> c1.increment()
>>> c1.value
11
>>> c2.value
11
>>> f.instance_count()
1
>>> f.get_instance(list)
[]
>>> f.instance_count()
2
8 points ~10 min

Recent Submissions

No submissions yet — hit Run Tests to try!

Hints

Store instances in a dictionary in __init__.
Check if key exists before constructing.
Return the stored instance if already present.
Python 3
All tests passed!
Test Results
Press Ctrl+Enter or click Run Tests to execute your code.