Singleton Design Pattern
When you need a Class to have only one instance and you want
to access from anywhere you can use singleton pattern. Let me explain a
scenario, if you have an instance of object and you need to change the
attributes of the objects from other classes then you need to pass the instance
via the constructor of other classes this cause some additional work and
complex code. So, whenever you need the instance you can call the
Singleton.getInstance(). It makes code simple an easy 😊.
You may wonder where can I use it if you are beginner but if you are a java developer you may see this pattern many times without acknowledging it as Singleton. for an example instance= FirebaseAuth.getInstance();
You may wonder where can I use it if you are beginner but if you are a java developer you may see this pattern many times without acknowledging it as Singleton. for an example instance= FirebaseAuth.getInstance();
Further the Singleton pattern can be extended to support specific
number of instances. You may need some number of instances from the class in
order to be memory efficient. In that case you can use this. It’s called multiton.
You may have used Singleton
- When Application needs one, and only one, instance of an object.
- If you are lazy initializing and if you think only one object is enough you can use it.
- When you need global access.
Class Diagram
Proper sample code (Threads are considered)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | public final class Singleton { //Object that will be given when get instance is called //instance is static and private so you cant acces from outside // instance is volatile so atomic private static volatile Singleton instance; //private Constructor can't be initialized outside // So if you want you can initialize in the class private Singleton() { //Add your code you want to put in the constructor } // public static method to get instance this will return instance //Only this method you can access the singleton object public static Singleton getInstance(String value) { // when you are using thread you may need 2 if clause and synchronised part //otherwise you can use one if clause //Check object is created if (instance == null) { //If 2 thread comes you have to check whether object is created // then you should access the only one thread inside Class level Lock synchronized (Singleton.class) { //Re check whether object is created because 2 threads can be accessed if (instance == null) { instance = new Singleton(); } } } return instance; } } |
Comments (0)
Post a Comment
Cancel