简体   繁体   English

如何实现@Singleton 注解?

[英]How can I implement @Singleton annotation?

Possibly a repeated question.可能是重复的问题。 But I need to implement something like但是我需要实现类似的东西

@Singleton
public class Person {
}

That will ensure only single instance of Person object.这将确保只有 Person object 的单个实例。

One way is to make constructor private.一种方法是将构造函数设为私有。 But that makes the Singleton annotation redundant.但这使得 Singleton 注释变得多余。

I could not really understand if I can really restrict object creation to single object without making the constructor private.我真的不明白我是否真的可以在不将构造函数设为私有的情况下将 object 的创建限制为单个 object。

Is that even possible?这可能吗?

No annotation can prevent a class from being instantiated. 没有注释可以阻止实例化类。 However, if you plan to implement something like a Dependency Injection framework, or just a simple object factory, then you can use reflection to read the annotation and prevent the class from being instantiated more than once, but I understand this is not the answer you were looking for. 但是,如果您计划实现类似依赖注入框架的东西,或者只是一个简单的对象工厂,那么您可以使用反射来读取注释并防止类被多次实例化,但我明白这不是您的答案正在寻找。

You can actually think about dropping the singleton pattern and moving to some more modern solution like a proper DI framework, which can give you the same result - with more flexibility. 您实际上可以考虑放弃单例模式并转向更现代的解决方案,例如适当的DI框架,这可以为您提供相同的结果 - 具有更大的灵活性。

public class ASingletonClass
{
    private static ASingletonClass instance = null;
    private ASingletonClass()
    {

    }

    public static ASingletonClass getInstance()
    {
        if(instance==null)
        {
             instance = new ASingletonClass();
        }
        return instance;
    }
}

This is the right way to implement singleton. 这是实现单例的正确方法。 The annotation cannot stop people from calling the public constructor. 注释不能阻止人们调用公共构造函数。

You can also use lazy initialization of the class. 您还可以使用类的延迟初始化。 Example code as below. 示例代码如下。

class LazyInitialization implements PrintStatement {
   private static LazyInitialization instance;

   private LazyInitialization() {

   }

   static LazyInitialization getInstance() {
     if (instance == null)
        instance = new LazyInitialization();

     return instance;
   }

   @Override
   public void print() {
      System.out.println("I am inside");
   }
}

It is arguably best to have a stateless singleton:最好有一个无状态的 singleton:

public class Singleton {
    private static final Singleton INSTANCE = new Singleton();
    
    private Singleton() {}
    
    public static Singleton getInstance() {
        return INSTANCE;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM