In Java, if we create a class that wants the class to have only one object, then we can
1: Design The construction method of this class as private
2: Define a static method in the class that creates the object in the method
Packagetest;/** Sometimes we want a class to have only one instance at any given time, so we can design this class as a singleton pattern. * To design a class as a singleton mode, you need: * 1: The access modifier for the constructor method of the class is private * 2: Then define a static method in the class that creates the object of the class in the method **/ Public classSingleton {Private Static FinalSingleton INSTANCE =NewSingleton ();//Private Members Private intA = 0;//Private Members PrivateSingleton () {}//Construction Method Public Static synchronizedSingleton getinstance () {//methods of the class returnINSTANCE; } Public voidMethodA () {//member Methodsa++; System.out.println ("A =" +a); } Public Static voidMain (string[] args) {//Main MethodSingleton SG1 =singleton.getinstance (); Singleton SG2=singleton.getinstance (); Sg1.methoda (); Sg2.methoda (); System.out.println (SG1==SG2); }}
The creation of a class that can have only one instance in Java