Java中Singleton的其他方式 [英] Other Ways of Singleton in Java

查看:57
本文介绍了Java中Singleton的其他方式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是在考虑编写单例课程的其他方式.那么,该课程被视为单身人士课程吗?

Just i was thinking about the other ways of writing singleton class. So is this class considered as a singleton class?

      public class MyClass{
            static Myclass myclass;

            static { myclass = new MyClass();}

            private MyClass(){}

            public static MyClass getInstance()
            { 
                return myclass;
            }
       }

因为静态块仅运行一次.

as the static block run only once.

推荐答案

不,不是.您没有声明myClass private static final,也没有声明getInstance()static.该代码也没有真正编译.

No, it is not. You didn't declare myClass private static final, nor the getInstance() is static. The code also doesn't really compile.

这是单语习语:

public class MyClass {
    private static final MyClass myClass = new MyClass();

    private MyClass() {}

    public static MyClass getInstance() {
        return myClass; 
    }
}

应为private,以便其他任何人都不能直接访问它.它应该是static,以便只有一个.它应该是final,以便不能重新分配它.您还需要在声明期间直接 实例化它,这样就不必担心线程那么多.

It should be private, so that nobody else can access it directly. It should be static so that there's only one of it. It should be final so that it cannot be reassigned. You also need to instantiate it directly during declaration so that you don't need to worry (that much) about threading.

如果加载昂贵,因此您宁愿延迟加载Singleton,请考虑单个持有人惯用语,它按需进行初始化,而不是在类加载期间进行初始化:

If the loading is expensive and you thus rather prefer lazy loading of the Singleton, then consider the Singleton holder idiom which does initialization on demand instead of during classloading:

public class MyClass {
    private MyClass() {}

    private static class LazyHolder {
        private static final MyClass myClass = new MyClass();
    }

    public static MyClass getInstance() {
        return LazyHolder.myClass;
    }
}

但是,您应该提出一个大问号,是否需要 Singleton .通常不需要. 静态变量,枚举,工厂类和/或依赖项注入通常是更好的选择.

You should however put big question marks whether you need a Singleton or not. Often it's not needed. Just a static variable, an enum, a factory class and/or dependency injection is often the better choice.

这篇关于Java中Singleton的其他方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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