java中的Singleton类 [英] Singleton class in java

查看:114
本文介绍了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.

这是 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.

如果加载是昂贵的,因此你更喜欢延迟加载Singleton,然后考虑 Singleton holder 的成语按需初始化而不是在类加载期间:

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天全站免登陆