i Want to make a class and some methods in that class which interact with database. Many other classes Should call that methods.
Q1:is it possible to create only one instance of that class for others ?
Q2:Can i give methods as Static?
Q3:Is there is any alternative solution for stati开发者_如何转开发c and singleton for java database?
I have not used singletons in Java yet. However, there's a pretty good discussion on the subject at http://c2.com/cgi/wiki?JavaSingleton
Basically, you will make your constructor private along with a private static final instance variable. Then you will need a public static getInstance method that returns your instance. It gets a bit more complicated if you need to be thread safe, so read the linked article.
You can also use an enum with a single variable INSTANCE like below:
public enum EmployeeDAO {
INSTANCE;
static{
//Initialize connection info etc.
init();
}
private EmployeeDAO(){
//Constructor stuff
}
public Employee getEmployeesById(int id){
//Replace this with your data retrieval logic
return null;
}
public Employee getDeadBeatEmployees(){
//Replace this with your data retrieval logic
return null;
}
public Employee getAllStars(){
//Replace this with your data retrieval logic
return null;
}
public static void init(){
}
}
public class Employee{}
public class SillyCanuck{
public static void main(String args[]){
EmployeeDAO.INSTANCE.getEmployeeById(5);
}
}
精彩评论