If only one class uses your singleton object, then there are no visible differences in the number of objects created.
Assuming you need a classASing object using the Singleton approach
ClassASing { private static ClassASing obj = new ClassASing(); private ClassAsing(){...} public static ClassASing getNewObject(){ return obj; } }
Using the Singleton Approach
ClassB{ private ClassASing singObj = ClassASing.getNewObject(); }
- no matter how many instances of ClassB all of them created, the same ClassASing object will be used
using static link
ClassB{ private static ClassA sObj = new ClassA(); }
* regardless of how many instances of ClassB all of them created, the same link will be used pointing to the same object.
There are not many differences. 1 object is used in both cases.
Now, if u considers another sencario, you need an object in your two classes.
singleton approach
ClassB1{ private ClassASing singObj1 = ClassASing.getNewObject(); } ClassB2{ private ClassASing singObj2 = ClassASing.getNewObject(); }
- no matter how many instances of ClassB1 all of them created, the same ClassASing object will be used
- no matter how many instances of ClassB2 all of them created, the same ClassASing object that ClassB1 already uses will be used, so there is only one ClassASing object
Static Reference Approach
ClassB1{ private static ClassA sObj1 = new ClassA(); } ClassB2{ private static ClassA sObj2 = new ClassA(); }
- no matter how many instances of ClassB1 all of them created, the same sobj1 link pointing to the same object will be used
- no matter how many instances of ClassB2 all of them created, the same sobj2 link pointing to the same object will be used, but this object is different from the one created in ClassB1, so now you have two ClassA objects .
source share