如果我不想实例化一个类,我有什么选择? [英] If I do not want to instantiate a class, what are my options?

查看:50
本文介绍了如果我不想实例化一个类,我有什么选择?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有所有静态方法的类,该类基本上进行像ClassName#MethodName()这样的调用.

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

我希望此类始终都是不可实例化的,因此我将构造函数的可见性设置为private.当然,这可以避免从类外部创建任何实例. 我想知道是否有专门创造出来的技术术语或设计模式专门用于做我不知道的事情.

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?

推荐答案

我只是使用enum这个类是final,它是构造函数private,即使通过反射也不能保持不变.

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
    }
}

使用enum可以定义一个类的所有可能实例,因此,您已经定义了一个实例.

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

这篇关于如果我不想实例化一个类,我有什么选择?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆