java Singleton - prevent multiple creation through reflection

前端 未结 6 949
无人及你
无人及你 2021-01-30 22:52

I have a singleton like this.

public class BookingFactory {

    private final static BookingFactory instance;

    static {
        instance = new BookingFactor         


        
6条回答
  •  不要未来只要你来
    2021-01-30 23:54

    Make the assertion in the constructor:

    private BookingFactory() {
        if (instance != null)
            throw new IllegalStateException("Only one instance may be created");
        System.out.println("Object is created.");
    }
    

提交回复
热议问题