Well, a very general Singleton is an object which can only have one instance (ie we can only construct an object of that class during program execution). Schedule a Singleton in Java is very simple, all you have to do is prevent other classes have access to singleton constructor of my class, and how is that done? Well just have to make the private constructor, and then make a method that returns the only instance we created.
public class Singleton {
/ / THE ONLY INSTANCE TO BE CREATED
/ / SINCE THE CHARGE CREATING THE CLASS
private static Singleton instance = new Singleton ();
/ / DO THE BUILDER PRIVATE
/ / FOR INSTANCE CAN ONLY ITEMS FROM THE SAME CLASS
private Singleton () {}
/ / method to get the public
INSTANCE Singleton getInstance () {
return instance;}
}
In this example, the instance is created, since it creates the class, but sometimes it is better to create the instance until it is requested, then the code would be something like :
public class Singleton {
/ / CREATE THE REFERENCE
/ / EVEN TO TOP TARGETS NULL
private static Singleton instance;
/ / DO THE PRIVATE BUILDER
/ / so that only INSTANCE ITEMS FROM THE SAME CLASS
private Singleton () {}
/ / METHOD FOR THE INSTANCE
public Singleton getInstance () {
if (instance == null) / / If NULL
instance = new Singleton (); / / instantiate it
return instance;}
}
And with this Singleton create our class, and then we can schedule additional methods that are services to be offered. Greetings
0 comments:
Post a Comment