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

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

问题描述

我只是在考虑编写单例类的其他方法.那么这个类是否被视为单例类?

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 finalgetInstance() 也不是 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.

这里是 Singleton 习语:

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.

如果加载成本很高,因此您更喜欢单例的延迟加载,那么请考虑 单例持有者 根据需要而不是在类加载期间进行初始化的习惯用法:

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中单例的其他方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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