+ 3

Can anyone help me with understanding singleton pls?

it's the sample code used when I learned singleton, but I have no idea how it works.... Thanks in advance class Test { private static Test ob; public static Test getInstance() { if(ob==null) ob = new Test(); } //work return ob; } } public class Test4 { public static void main(String[] args) { Test ob1 = Test.getInstance(); Test ob2 = Test.getInstance(); if (ob1==ob2) System.out.println("same"); else System.out.println("different"); } }

1st May 2017, 5:09 AM
Sasha
Sasha - avatar
3 Respostas
+ 6
you still need a private constructor to make this work static objects never change; if you have an object that holds a private attr of itself, STATIC, it never changes, therefore a singleton. if you make a private constructor nobody but the class itself can make an instance of it. then when you create a static function in test like you did above, you cna get that static private object in the class, what is indeed the class itself. So there you go: singleton check https://sourcemaking.com/design_patterns/singleton for singelton patern and others
1st May 2017, 5:37 AM
Harm Zeinstra
Harm Zeinstra - avatar
+ 4
Ooh, it's great to get some feedback on my help, thank you! Can you mark me as answer if you are satisfied?
1st May 2017, 2:48 PM
Harm Zeinstra
Harm Zeinstra - avatar
+ 1
Thanks! That helped me a lot!!
1st May 2017, 7:41 AM
Sasha
Sasha - avatar