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

徘徊边缘 提交于 2019-12-03 13:29:39

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.

Not much practical difference, but somewhat of a philosophical difference.

I would recommend the singleton approach here - you're really describing a type of Data Access Object (DAO), albeit at a high level.

Some thoughts on why:

  • A Factory style approach to creation of the DBManager itself (i.e., DBManagerFactory) would make unit testing easier; it lends itself to the dependency injection model.

  • A class with a bunch of static methods is generally assumed to be a switchblade/utility kind of class with no over-arching theme (i.e., independence between methods). Think of a class like StringUtils -- people assume that there's no general state to the class.

  • At a crass level, with the "all static methods" approach, you're creating a lot of work for yourself in that you need to keep typing static for every method. Again, you can just have a DBManagerFactory that simply has a single static method for creating the DBManager, which ends up being a singleton.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!