lundi 27 janvier 2020

Singleton pattern execute ordering issue

I'm trying to learn singleton design pattern.the code is as follow:

public class Model {

    private static final Model INSTANCE = new Model();

    public static void main(String[] args) {
        Model.getInstance();
    }

    private Model(){
        System.out.println("constructor");
    }

    public static Model getInstance(){

        System.out.println("I hope to be printed first!");
        return INSTANCE;
   }
}

I expect the code to print I hope to be printed first! first, and then go through class constructor. but the code output is reverse :

constructor
I hope to be printed first!

I cant understand why the class is instantiated first?

Aucun commentaire:

Enregistrer un commentaire