tags:

views:

60

answers:

3

I have one department class.I want to create one instance department with value HR and one instance of department with value Admin, when my application loads(console app) and then i want to use those instances throughout my program.How can i use same instances everywhere in different classes?.For example i read a employee from csv file and then create a employee object.Now to create a employee object i must use the department object.I have to set proper value of department depending on the value of department read from file.How to do it

+2  A: 

You are looking for an instance of the singleton pattern, which you can implement by declaring your constructor private and keeping a static reference variable initialized in the getter. Something like:

private static Department hr = null;

private Department() {
}

public static synchronized Department getHRInstance() {
    if (null == hr) {
        hr = new Department();
    }
    return hr;
}

from the rest of your code you can call Department.getHRDepartment() and likewise for the Admin department, which simply maps to a second static variable. (For more than 2 singletons you might want to look at using a map to store instances or using an Enum class for defining the singletons.)

A singleton instance has the drawback that dependency injection is difficult to accomplish, making building JUnit tests difficult or impossible. For most singleton patterns used it is actually better to initialise "singleton" instances while initialising your application and passing them on to the classes using them by passing them via their constructor, or by creating an object factory that passes the singleton references after creating its object instances.

rsp
+1 for meantioning the drawbacks very cleary. Excellent answer. (Static) Singletons **s\*\*k** so much.
Willi
+1  A: 

Not directly an answer to your question, but your formulation makes me think that maybe what you want is an enum. If your department is a simple value, with no complex state or behaviour, it might be a good candidate for an enum.

Have a look at the enum tutorial : http://download.oracle.com/javase/tutorial/java/javaOO/enum.html

Guillaume
+1  A: 

You need a Singleton. There are several ways to implement it, being the most widely known the solution posted by rsp. A nice trick is to have an enum with only one value.

manolowar