所有静态方法和应用单例模式有什么区别? [英] What is the difference between all-static-methods and applying a singleton pattern?

查看:131
本文介绍了所有静态方法和应用单例模式有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个数据库来存储有关我网站用户的信息(我正在使用stuts2,因此使用Java EE技术)。对于数据库,我将制作一个DBManager。我应该在这里应用单例模式,还是使它的方法是静态的?



我将使用此DBManager来添加,删除和更新用户配置文件等基本功能。除此之外,我将使用所有其他查询目的,例如,了解用户名是否已经存在,并将所有用户用于管理目的以及类似的内容。



我的问题




  • 单身人士模式的好处是什么?

  • 哪个事情最适合这里?所有的静态方法或单例模式?

  • 请比较两者。



/ p>

shahensha



PS数据库比这更大。在这里我只谈论我将用于存储用户信息的表。

解决方案


我应该在这里应用单例模式,还是使其所有方法静态?


两者皆无。 只需创建一个



在一个简单的servlet容器中,您可以使用 ServletContextListener 为此。在webapp的启动过程中,创建一个并将其放在应用程序范围内,由 ServletContext#setAttribute()。在webapp生命周期中,所有servlet都可以使用它。对于基本的启动示例,您可能会发现本文有用。


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.

解决方案

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.

这篇关于所有静态方法和应用单例模式有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆