If I do not want to instantiate a class, what are

2019-07-06 12:11发布

问题:

I have a class with all static methods which basically makes calls like ClassName#MethodName().

I want this class to be non-instantiable at all times and so I have set the constructor visibility to be private. This certainly avoids any instance of it being created from outside the class. I want to know if there is any technical term coined or any design pattern specifically designed for doing exactly this which I do not know of.

Also this does not stop me or any other developer from instantiating it from within the same class. I want to know if it is possible to prevent doing that but keeping the same class behavior. Also, what are the other options, if any?

回答1:

I just use an enum The class is made final, it's constructors private and it is not instancable even via reflection.

public enum Utility {;
    public static void staticMethod() {
        // do something
    }
}

Using an enum allows you define all possible instance of a class and in this cause you have defined there can't be any.



回答2:

i would write like:

public class MyClass{
// Suppress default constructor for noninstantiability
    private MyClass(){
          throw new AssertionError();
    }
          . . . . . 
          . . . . . 
          . . . . . 
}

Because the explicit constructor is private, it is inaccessible outside of the class. The AssertionError isn’t strictly required, but it provides insurance in case the constructor is accidentally invoked from within the class. It guarantees that the class will never be instantiated under any circumstances. This idiom is mildly counterintuitive, as the constructor is provided expressly so that it cannot be invoked. It is therefore wise to include a comment, as shown above.

source.



回答3:

I think the best approach is using the private constructor as you said:

public final class MyClass {    

    private MyClass() {}

    public static void do() {}
}

and also make it final so no one can extend your class.



回答4:

Make the constructor private and the class final.