samedi 7 mars 2015

Is it possible to initialize final fields while using the holder pattern to create a singleton?

Given the normal class



public class Dog{
private static final int LEGS;
private static final int TEETH;

public Dog(int legs, int teeth){
LEGS=legs;
TEETH=teeth;
}
}


I can get an instance using Dog dog = new Dog(4,21);


But if I want to turn Dog into a singleton using the holder pattern, I normally do



public class Dog{

public static Dog getInstance(){
return DogHolder.INSTANCE;
}

private static class DogHolder{
public static final Dog INSTANCE = new Dog();
}

private Dog(){
}
}


The obvious problem with my singleton pattern is that I am not able to initialize the final fields LEGS and TEETH. Hence my question: How do I initialize the final fields while still using the holder pattern to create my singleton? What I mean in codes is that I want to change my getInstance() to getInstance(int legs, int teeth) while still using the holder pattern.


Aucun commentaire:

Enregistrer un commentaire