Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I make an object available to all classes in my project without including it as a field?

I am making a text adventure engine in Java, and in order to save memory, I have a database object that holds all the currently scraped items from an XML document. I want to use it from several different classes. How can I make it available to my classes? Currently I'm using a null static field with an appropriate mutator method.

like image 254
David B Avatar asked Dec 27 '22 02:12

David B


2 Answers

It might be useful to use a Singleton for this.

like image 107
VeeArr Avatar answered Apr 05 '23 23:04

VeeArr


You can use a enum type. Joshua Bloch says in his book Efective Java: a single-element enum type is the best way to implement a singleton.

public enum Elvis {
    INSTANCE;
    public void leaveTheBuilding() { ... }
} 
like image 35
Paul Vargas Avatar answered Apr 05 '23 23:04

Paul Vargas