How to create a variable that can be set only once but isn't final in Java

后端 未结 12 1594
感情败类
感情败类 2020-12-14 05:43

I want a class that I can create instances of with one variable unset (the id), then initialise this variable later, and have it immutable after initial

12条回答
  •  南笙
    南笙 (楼主)
    2020-12-14 06:26

    I think the singleton pattern might be something you should look into. Google around a bit to check if this pattern meets your design goals.

    Below is some sudo code on how to make a singleton in Java using enum. I think this is based off Joshua Bloch's design outlined in Effective Java, either way it's a book worth picking up if you don't have it yet.

    public enum JavaObject {
        INSTANCE;
    
        public void doSomething(){
            System.out.println("Hello World!");
        }
    }
    

    Usage:

    JavaObject.INSTANCE.doSomething();
    

提交回复
热议问题