Singleton Pattern in Java
This has the same purpose as static variable in java. Can be initialized only once!
Problem solved :
Creating multiple objects of java class having same data is wasting memory, degrading performance. It is recommended to create one object and use it multiple times (at certain use-case)
When to use?
- For a class which does not contain attribute or any state. (E.g. Conversion class, Validation class)
- The class, for which we want to create only one object or instance. (Logger, Database etc)
- In Firebase, database instance is created only once:
Code Findings:
- It is used in react-redux (I believe). If you see, the redux store is initialized only once.
store.js
containers/Component.js
redux store is apparently the single point of state data.
Example again:
Suppose your back-end is live. During some point in time, there where some Exceptions thrown. In the end of the day, these Exceptions are to be pushed into the DB and analysed.
For this scenario, we need to keep a single object(Exception Queue) to hold Exceptions thrown from various Classes, rather than, instantiating a new Exception Queue every time.
Project Structure:
Implementation in Java:
- Singleton Class is created
- private constructor
- public Class getInstance() calls the private constructor
2. Driver to test the program
Found it Interesting?
Please show your support by 👏. To read the complete series, click below.
Reference:
- https://www.javatpoint.com/singleton-design-pattern-in-java
- https://www.quora.com/What-is-singleton-design-pattern-1
Disclaimer:
I myself, has just started learning, design patterns. If you find any issues please feel free to post them in the comments section below. Thank you for reading so far 😄