Singleton Pattern says that just"define a class that has only one instance and provides a global point of access to it".
In other words, a class must ensure that only single instance should be created and single object can be used by all other classes.
Early Instantiation: Creation of instance at load time. Lazy Instantiation: creation of instance when required.
Saves memory because object is not created at each request. Only single instance is reused again and again.
Singleton pattern is mostly used in multi-threaded and database applications. It is used in logging, caching, thread pools, configuration settings etc.
To create the singleton class, we need to have static member of class, private constructor and static factory method.
It gets memory only once because of static, itcontains the instance of the Singleton class.
It will prevent to instantiate the Singleton class from outside the class.
This provides the global point of access to the Singleton object and returns the instance to the caller.
- Open command prompt.
- Go to the loaction where you have stores the project using command
cd location ( location of the Java Project folder )
- Compile both Tank.java and TankTest.java file.
- Run TankTest.java file.