简体   繁体   English

如何从不同的类访问同一个对象

[英]How can I have access to the same object from different classes

How can I have access to the same object from multiple classes?如何从多个类访问同一个对象?

I'm making a Java app for bookstore management using window builder, there are different types of users, and different panels for each user.我正在使用窗口构建器制作一个用于书店管理的 Java 应用程序,有不同类型的用户,每个用户都有不同的面板。

I need to have access to an updated object of the class bookStore (for example) to access the updated list of books, the list of users, so I can add or make changes on it.我需要访问类 bookStore 的更新对象(例如)以访问更新的书籍列表、用户列表,以便我可以添加或更改它。 I took a look at singleton design pattern but I don't know if I can use it on this kind of situations.我看了一下单例设计模式,但我不知道我是否可以在这种情况下使用它。 Should I use it?我应该使用它吗? And if so, are there any cons?如果是这样,有什么缺点吗?

Is there another way to do it?还有另一种方法吗?

Yes, you could use a singleton for that.是的,您可以为此使用单例。 The easiest way is to use Spring , declare your BookStore as a Bean in your Application class:最简单的方法是使用Spring ,在 Application 类中将 BookStore 声明为 Bean :

@Bean
public BookStore getBookStore(){
  return new BookStore();
}

And then, in every class where you need to reference it, declare your bookStore as an @Autowired object so Spring automatically finds your BookStore singleton and injects it.然后,在您需要引用它的每个类中,将您的 bookStore 声明为@Autowired对象,以便 Spring 自动找到您的 BookStore 单例并注入它。 For example:例如:

@Service
public class BookService {

  @Autowired
  private BookStore bookStore; //This variable will reference your BookStore singleton.

  public List<Book> getBooksFromStore(){
    return bookStore.getBooks();
  }

}

You can learn more about Spring here: https://www.baeldung.com/spring-tutorial您可以在此处了解有关 Spring 的更多信息: https : //www.baeldung.com/spring-tutorial

This is just an example so you can learn about singletons, but in a real world scenario you should use a database to persist your data, since the singleton will only hold data until your application stops executing.这只是一个示例,因此您可以了解单例,但在实际场景中,您应该使用数据库来保存数据,因为单例只会保存数据,直到您的应用程序停止执行。

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

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