mercredi 14 juillet 2021

How to create Singleton for class having multiple properties?

Is it possible to create Singleton for class like:

class Employee{
private long id;
private String name;
}

Is following code a valid Singleton implementation?

class Employee{

private long id;
private String name;
private static Employee instance = null;

private Employee(long id,String name){
    this.id=id;
    this.name=name;
 }

public static Employee getInstanceUsingDoubleLocking(long id,String name){
   
    if(instance == null){
        synchronized (Employee.class) {
            if(instance == null){
                instance = new Employee(id,name);
            }
        }
    }
    return instance;
 }

}

If not then how can I create Singleton for such class?

Aucun commentaire:

Enregistrer un commentaire