简体   繁体   English

如何创建可以保留在内存中并可供所有其他类访问的类的对象?

[英]How can I create an object of a class that can remain in memory and be accessible to all other classes?

I parse a html document and save the data in class. 我解析一个html文档,并将数据保存在类中。 how can I access that class from different classes without initiating it again because I want to use one version of that class 如何从不同的类访问该类而又不必再次启动它,因为我想使用该类的一个版本

Why dont you set it to a static variable? 为什么不将其设置为静态变量?

public static HtmlData data; 公共静态HtmlData数据;

private void parse() { ··· data = result; private void parse(){···data =结果; } }

// now you can use the data object anywhere in your code by calling HtmlData.data //现在,您可以通过调用HtmlData.data在代码中的任何位置使用数据对象

As said in your comments, a singlton would be the way to go. 正如您在评论中所说,辛格尔顿是最好的选择。 A singleton is holding and managing its own instance, so that you can return this same instance to everyone asking for it. 单例正在持有和管理自己的实例,因此您可以将同一实例返回给要求它的每个人。

catchword 'dependency injection', best practice, rather than calling the factory via static access directly, is holding the instance in a private property within the class you need it and "inject the dependency" with public setter in a centralized way, while initializing your application. 最好的口号是“依赖注入”,而不是直接通过静态访问来调用工厂,而是将实例保存在您需要的类中的私有属性中,并以集中方式通过公共设置器“注入依赖”,同时初始化您的应用。

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

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