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
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With