Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between all-static-methods and applying a singleton pattern?

I am making a database to store information about the users of my website (I am using stuts2 and hence Java EE technology). For the database I'll be making a DBManager. Should I apply singleton pattern here or rather make all it's methods static?

I will be using this DBManager for basic things like adding, deleting and updating User profiles. Along with it, I'll use for all other querying purposes, for instance to find out whether a username already exists and to get all users for administrative purposes and stuff like that.

My questions

  • What is the benefit of singleton pattern?
  • Which thing is most apt here? All static methods or a singleton pattern?
  • Please compare both of them.

regards

shahensha

P.S. The database is bigger than this. Here I am talking only about the tables which I'll be using for storing User Information.

like image 455
shahensha Avatar asked Jan 06 '11 18:01

shahensha


2 Answers

Should I apply singleton pattern here or rather make all its methods static?

None of both. Just create one.

In a simple servletcontainer, you can use ServletContextListener for this. During webapp's startup, create one and put it in the application scope by ServletContext#setAttribute(). It'll be available to all servlets during webapp's lifetime. For a basic kickoff example, you may find this article useful.

like image 113
BalusC Avatar answered Nov 06 '22 03:11

BalusC


I don't know the internals of EE, but typically the difference between a static class and a Singleton is instantiation - with the static class, there is no actual instantiation, no member data, no reference to an object. So the practical difference is...not much.

I think the real benefit here is conceptual...static methods and properties are methods which apply to the abstract concept of the class, and not to a particular instance. If you create a singleton user object here, who is that user? Why does he have the particular context to create and update profiles? I don't think the concept maps very well.

It makes much more sense to me to say UserProfile.Update(username, password, firstName...). You're saying "perform the task Update from the abstract concept of UserProfile on this particular set of data".

Keep in mind here that my use of the word abstract is strictly figurative, and not in the computer science sense of the word.

like image 31
Chris B. Behrens Avatar answered Nov 06 '22 04:11

Chris B. Behrens