I am studying a basic software development pattern.
The basic implementation of singleton classes is written as follows:
public class MyObject{
private volatile static MyObject obj;
private MyObject(){}
public static synchronized MyObject getInstance(){
if(obj==null)
obj=new MyObject();
return obj;
}
}
But since I have the wrong call, synchronous methods can be tough.
While I am returning the book, I presented this implementation of the Singleton class:
public class MyObjectHolder {
private volatile static Supplier<MyObject> myObjectSupplier = () -> createMyObj();
public static MyObject getMyObject(){
return myObjectSupplier.get();
}
private static synchronized MyObject createMyObj(){
class MyObjectFactory implements Supplier<MyObject> {
private final MyObject clockTimer = new MyObject();
public MyObject get() { return clockTimer; }
}
if(!MyObjectFactory.class.isInstance(myObjectSupplier)) {
myObjectSupplier = new MyObjectFactory();
}
return myObjectSupplier.get();
}
public static class MyObject{
private MyObject(){
}
public void someMethod(){
}
}
}
...
{
MyObjectHolder.MyObject obj = MyObjectHolder.getMyObject();
}
Now that the first call to 'createMyObj ()' has been completed, there is no heavy burden of invoking a method synchronously, but not if not checked.
Do you think that something is wrong with this type of implementation?
ps. MyObject should not be the inner class of MyObjectHold, but I thought it looked good.
source
share