Understanding Singleton design pattern
- Creation of only one instance of the singleton class.
- if an instance exists, we will again provide the same object.
code description:
The new method in the code is a special method of python to instantiate objects which is used to control the objects creation. The object gets created with the new method , but before creating the object, it checks whether the object already exists. The hasattr method is a special method in python to know if an object has a certain property. It is used to see if the class object has the instance property, which checks whether the class already has an object.Here in our code we have requested s object before sA object. When s object is requested the hasattr() detects that object does not exists and hence s allocates the new object instance. When s1 object is requested,hasattr() detects that objet already exists and hence s1 allocates the existing object instance (located at 0x000002345C7A5B48).
A Real-world scenario - the singleton pattern
This is a database application to show the use of Singletons. Lets us consider an example of cloud service that involves multiple read and write operation in the database. The complete cloud service is split across multiple services that performs database operations.An action in the UI internally will call an API, which results in DB operation.
The database is shared across different service. So in order to design the cloud service better, the following points must be managed.
The Consistancy should be maintained across the operations in the database.
Memory and CPU utilization should be optimal for the handling of multiple operation on the database.
We will go through factory design pattern in the next topic of design patterns in python.
View the code as well as output in the github source:
https://github.com/kcsanjeeb/Python-design-patterns/blob/master/singleton.ipynb