![]() |
VOOZH | about |
The Singleton Pattern ensures a class has only one instance throughout a program and provides a global access point. It is commonly used for managing shared resources like databases, logging systems or file managers.
This example shows how a class creates only one object and returns the same object every time it is called.
True
Explanation:
All Python modules are singletons by default. Any variables or functions defined in a module are shared across imports. For Example: Below example, three files, Singleton.py, samplemodule1.py and samplemodule2.py share a variable from Singleton.py
Output
Here, the value changed by samplemodule1 is also reflected in samplemodule2.
Explanation:
Classic Singleton creates an instance only if it does not exist. Otherwise, it returns the already created instance.
True Singleton Variable
Explanation:
Subclass Example: Let's check what happens when we subclass a singleton class.
Output
False
Singleton Variable
Explanation:
Borg Singleton allows different instances to share the same state.
False Shared Variable
Explanation:
Borg Singletons share state across instances. Resetting allows creating a fresh instance with an independent state while keeping the Borg structure.
Output
Resetting the shared state removes previous attributes. Accessing val now causes an AttributeError.
Traceback (most recent call last):
File "example.py", line 12, in <module>
print(nb1.val)
AttributeError: 'NB' object has no attribute 'val'
This example uses the Classic Singleton pattern to build a simple multi-threaded web crawler. A single shared crawler instance stores the URL queue, visited pages, and downloaded images, while multiple threads access the same data to crawl pages and download images without duplication.
Output
Let's look into the downloaded images and python shell output.
Explanation: