简体   繁体   English

仅具有一个实例的类,该实例可从所有其他类访问

[英]Class with only one instance that is accessible from all other classes

I need to create a class that contains a lot of information (slow to initialize). 我需要创建一个包含很多信息的类(初始化缓慢)。 I am trying to access this class from my other classes. 我正在尝试从其他班级访问该班级。 This class should only be created once because it is slow to load and takes a lot of memory. 此类仅创建一次,因为它加载缓慢且占用大量内存。 My only idea of how to do this is to create an instance of the class in the loader class and then pass it from class to class as I switch through them. 我唯一的想法是在加载器类中创建该类的实例,然后在切换它们时将其从一个类传递到另一个类。

I feel like there is a better way to do this. 我觉得有更好的方法可以做到这一点。 I thought about making all the methods and variables in this class static but then I would still have to make a new object in each new class which I think would then re-initialize the object(which I don't want to do). 我考虑过将此类中的所有方法和变量设为静态,但是我仍然必须在每个新类中创建一个新对象,然后我认为该类将重新初始化该对象(我不想这样做)。

I am not sure if there is a better way to do this... thoughts? 我不确定是否有更好的方法来做到这一点...想法?

What you are asking for is a singleton. 您要的是单身人士。 The easiest way of doing this is using an enum instance - this is the simplest way to takes care of thread-safety issues that can arise when you try to use static members. 最简单的方法是使用枚举实例-这是解决尝试使用静态成员时可能出现的线程安全问题的最简单方法。

That said, singletons are generally considered to be a sign of an architecture problem. 也就是说,单例通常被认为是体系结构问题的标志。 This is a general rule, and you may very well have good reasons for doing it this way - just make sure that your reasons are valid. 这是一条一般规则,您很可能有这样做的充分理由-只需确保您的理由是正确的即可。 The singleton anti-pattern tends to create strong coupling between different layers of the application, leading to fragile, difficult to test code. 单例反模式往往会在应用程序的不同层之间创建强耦合,从而导致脆弱,难以测试的代码。

As an alternative, if dependency injection is an option for you, then construct your object once and inject it where needed. 或者,如果依赖项注入是您的选择,则构造一次对象,然后将其注入到需要的地方。 Note that you don't have to have a DI framework to use dependency injection (you can just pass the object in to the constructors of the dependent objects). 请注意,您不必具有DI框架即可使用依赖项注入(可以将对象传递到依赖对象的构造函数中)。 This allows you to be hyper-aware of the locations where that singleton is actually used. 这使您可以高度了解实际使用该单例的位置。

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

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