how to use one instance of object throughout my application - java

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

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.

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

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.

Related

Java 7 - simple object to hold static values and shared methods

You have some object that just contains static data and static methods. Lets call it DataHoldingClass. You want this because the data is then easily accessible in code by writing object.VALUE and object.method(). It's all just for laziness and simplicity. And we all agree that this is important.
But some of the static method()s are common in your code, so you want to share them among DataHoldingClasses. The OOP approach is to define some abstract class BaseClass, put common methods there and then let the DataHoldingClass extends BaseClass.
But it's not possible, because each DataHoldingClass has different values and you cannot reach that values from abstract class. If you define public static final String VALUE in abstract, all subclasses would have only one shared VALUE and if you define separate VALUE in each DataHoldingClasses, you cannot create static String method() { return NAME; } in abstract class, because NAME isn't defined in abstract yet.
The only way to make it work is create values and methods non-static. Then the methods will be inherited from abstract class BaseClass and will work with DataHoldingClass specific values. But now you have to create new class instance every time you want access the data. Hmm, we've advanced from splash to mud.
But we can solve it, right? Just create some object to hold instances or make the DataHoldingClass a singleton. But this does not seem to be much better.
Another way might be to pass values to static methods by parameter, but calling some object method with the same object values as parameter seem weird and remember, we do this because of laziness, so we don't want to write object name two times.
Whats your way to storing such data objects? Currently, I'm using singletons, but I feel there must be some better way. Any idea?
Edit
example of usage:
Lets create such DataHoldingClass for each table in our database. Each table has own constants like COLUMN_ID = "_id" and TABLE_NAME = "evilTable" and every table have methods like insert() or update(). The methods are same for every table but can be overriden for some tables. The Constants are different. And I want define it as constants, because it is then easily accessible like Table.TABLE_NAME etc.

MVC in Java - Static controller?

I have a number of different organisations, each of which is an instance of the Organisation class. This contains getters and setters for instance variables, the setters contain validation where appropriate. It also has a few other odds and ends - overwritten toString(), equals() and hashCode() for example.
I have OrganisationView extends JFrame which accepts an Organisation and displays it in the GUI, and includes listeners for the various functions.
I understand from this question how this should all fit together and work with OrganisationController. What I'm not clear on is how many, if any, instances of OrganisationController I need. Is it one per organisation, and storing the organisation it refers to as an instance variable? Because it seems easier just to declare OrganisationController as static and call its methods directly from OrganisationView giving OrganisationView a method something like:
private boolean deleteButtonPressed(){
return OrganisationController.deleteOrganisation(this.organisationDisplayed)
}
(and perhaps some other business logic, but that's by the by)
OrganisationView, by the way, is called each time that particular display is needed, and is passed the organisation to show.
My question is: If it is better to have a separate instance of OrganisationController for each Organisation then why? It seems like an unnecessary amount of objects differing only in one instance variable. Or are static controllers acceptable?
I would not make it static. Use a singular controller and separate your views into directories. Then you can organized each part accordingly. You don't want to statically call the controller from the view. You want each person who logs in to have their own instance. Its simply a matter of separating out your views, models etc into separate folders and directories. I'm actually working on a project right now where I do this. I prepend each section with a keyword so as to keep it separate.
You can use the Singleton pattern to make sure that you only create one Controller && also access your controller in a static way.
I suggest you go for the enum implementation of Singleton which would be something like this
public enum OrganisationController{
INSTANCE;
// you can have fields
private final example;
// and also methods
public boolean deleteOrganisation(Organization org){
// do whatever here
}
}
And you can invoke methods in a static-looking way
OrganisationController.INSTANCE.deleteOrganization(org);

Should I use static methods for a menu class in a employee payroll console system?

My program is a small program that has an employee class and another Menu class that is used to manipulate an array of employees in the console program. Should the methods of the Menu class be declared static?
Some examples of the methods are addEmployee, updateEmployee and showEmployees. Every employee object is stored in an Employees array, which will be used by many other methods, such as to show all employees by passing in the array.
If the methods are declared static, then all I have to do is to pass in the array into the static methods is such as
Employee[] employees = new Employee[50];
Menu.showEmployees(Employees);
//other example methods that manipulate the array
Menu.methodX(Employees);
Menu.methodY(Employees);
Menu.methodZ(Employees);
However, if not static, I have in mind to have a constructor for the Menu class that would take in an employees array, after which the menu object can manipulate the array directly as its member:
Employee[] employees = new Employee[50];
Menu menu1 = new Menu(Employees);
menu1.showEmployees();
//other example methods that manipulate the array
menu1.methodX();
menu1.methodY();
menu1.methodZ();
I am aware that static methods should only be used as utility methods, but sometimes static methods can be used if convenient and if the system is not going to expand. Which is the better practice in this case?
A static method is useful for invoking functions on a class that don't require state. The most venerable example of this is Integer.parseInt; we don't require an instance of an Integer to parse a String into an int.
If you find yourself passing the state repeatedly to static functions, it's a wiser move to use an instance as opposed to all-static functions/variables. Specifically in this case, since your operations absolutely do depend on state, then having static functions makes little sense.
...some examples of the methods are addEmployee, updateEmployee and
showEmployees. Every employee object is stored in an Employees array,
which will be used by many other methods, such as to show all
employees by passing in the array.
Here is a general rule:
Avoid global state.
Global state makes your programs fragile, insecure, and difficult to maintain. Global state is the anti-thesis of encapsulation (which describes the principle in which data is hidden inside modular, decoupled units).
Global state is primarily made up of the static instance fields of a class. Observing the rule above, the answer to your question depends on how your data model is defined:
Employee data stored in static instance fields. In this case, your static employee methods will be able to directly access and modify the static employee data. You should not do this, however. It is bad design. Any code that has access to your class can access and alter employee data causing security problems, consistency problems, and maintenance problems.
Employee data stored in non-static instance fields. In this case, your static methods cannot directly access the non-static employee data. To solve this, you can pass a reference to the instance you wish to modify as an argument to the method. There will still be possible concurrency problems and these will need to be considered in a multithreaded design. This design has better encapsulation, should be less fragile, and more secure.
The best design would be to carefully construct a domain object model. Your goal should be to have each module encapsulate all of the state and the behavior that operates on that state. In this way, you should find that your goals can be accomplished without as many static methods. As a benefit, your program will contain modules that are decoupled, can evolve independently, are easier to maintain, and are more secure.
The fact that you have a Menu class suggests that your design may be suboptimal. A Menu has no obvious relationship to an Employee; it does not make intuituitive sense that a Menu -has an- Employee. Your classes are probably not as decoupled as they could be.
I think ,dear ,u should use static...bcz if u specify any method static ...u need not to create an object of the class to call the method .. U can directly call it by using (class_name.method_name) ...it saves memory that was being waste into creating an object. Both method are right.......but I have to tell another thing that in java Menu class is a static class. ...so u have to use static keyword to methods

"hide" mutable objects with a factory method

I read some lines in Effective Java: Programming Language Guide
Joshua Bloch and find out that I should avoid the usage of mutable objects. Because of I read the book I know how to make a mutable object immutable (e.g. usage of private and final modifier).
Well however I have a "dummy" data holder class with some private fields. Each field is accessable with a get method and also a corresponding set method. So because of this set methods objects of this class are not immutable.
The question is now how to avoid these set methods? Pass all (e.g. 20) parameters to the object constructor? I think this is not really good design because I have to keep care of the order of parameters, have to pass null references if I do not want to set a special parameter and so on.
So I think about following approach:
Create an interface with all get methods and let it implement from dummy data holder class
Create an abstract class with a private constructor and a static factory method which returns the "get" interface instance of the data holder object.
In the static factory method I configure the data holder object with all necessary set methods
Make the data holder class package private so that a object can only be instanciated over the static factory method which is defined in the abstract class
In the next step I store the configured and created data holder objects in a list.
What is the best approach to read out a object an modify the object although it is immutable? Create a new object with a static factory method which sets the new value internally and replace it with the object in the list?
As #NilsH pointed out: you should go for the Builder pattern, ideally based on a fluent interface.
As an example, you may look at make-it-easy.

Serializing ENUM Singleton

I'm trying to serialize an ENUM singleton instance (as described by Joshua Bloch in his book Effective Java) to a file. The ENUM instance is a simple JavaBean as this:
public enum ElvisFan implements Serializable{
INSTANCE;
private int totalSongsListened;
private ElvisFan(){
totalSongsListened=0;
}
public void set(int v){
totalSongsListened=v;
}
public int get(){
return totalSongsListened;
}
}
}
I'm successfully using this enum all over my program but when I write this enum to a file using snakeyaml, I just have !!com.chown.ElvisFan 'INSTANCE' in my test.yaml file. This is what I'm doing:
Yaml yaml = new Yaml();
yaml.dump(ElvisFan.INSTANCE, new FileWriter("test.yml");
I also tried this without any luck:
JavaBeanDumper dumper = new JavaBeanDumper();
dumper.dump(ElvisFan.INSTANCE, new FileWriter("test.yml");
Can someone please guide me on this. Thanks!
[Edited]
Code correction.
Singletons don't reakky make any sense. Serialisable singletons make even less sense. There is by definition only one singleton. So when you deserialise a singleton you are not going to get a new object. You will get the same old instance with the same old data.
Enums serialisation is handled specially. They are represented by name and type. No other state is saved, because as previously stated that doesn't make any sense.
I suggest modifying your code to avoid mutable statics.
Enums should not have mutable state. Serialising enums with a single instance can make sense where they implement some other class, such as Comparator, or are use as a key or somesuch.
SnakeYAML treats a List as a sequence not as a mapping even though List has also getters (getFirst()).
Why do you expect enum to be serialized as map ?
You have to provide a custom Representer to dump such an unusual enum as a JavaBean.
Tests contain a lot of examples how to write a custom Representer/Constructor.

Categories