本文介绍了单例方法是否适合访问/维护数据库和Internet连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我正在开发一个需要本地数据库连接并使用一些Web服务来来回发送和接收数据的应用程序.

  • 每当需要数据库操作时,我都会创建一个对象 DbConnection (这是我用来获取我的类的名称数据库),并在同一数据库上执行操作.

  • Whenever I need and database operation then I create an object of myDbConnection class (this is the name of class I am using to get mydatabase) and perform operations on the same.

类似于互联网连接,我使用 DefaultHttpClient 和创建一个相同的 static 对象,并在需要获取时连接并调用 webservice ,我创建了 HttpResponse 对象并获取响应数据.

Similarly for connecting with internet I use DefaultHttpClient andcreate a static object of the same, and whenever need to getconnection and call a webservice I create HttpResponse objectand get response data.

1)我是否使用正确的方法或模式?

2)另外,还要关注点2的问题,静态和单例的工作方式是否相同?

推荐答案

我不这么认为.如果对连接使用单例(或静态),那么在需要多个连接的环境中使用/重用代码将变得很困难.例如如果您将应用程序设置为多线程,或者将其转换为库.

I don't think so. If you use a singleton (or a static) for the connection then you make it difficult if your code needs to be used / reused in a context where there may need to be more than one connection; e.g. if you make your application multi-threaded, or turn it into a library.

Singletons在可测试性方面也有问题...

Singletons also have problems with respect to testability ...

通常来说,您可以使用Singletons(或静态变量)进行的任何操作,也可以使用某种上下文参数进行的操作.依赖注入(DI)框架提供了一种巧妙的方法来创建共享对象并将其连接"到需要它们的其他对象中,而无需使用单例或静态方法.另外,您也可以通过多种方式手动完成此操作.

Generally speaking, anything you can do with Singletons (or statics) you can also do with a context parameter of some kind. Dependency Injection (DI) frameworks provide a neat way to create the shared objects and "wire" them into the other objects that need them ... without using singletons or statics. Alternatively, you can do it by hand, in a variety of ways.

单子是一种设计模式.静态是Java语言功能,可用于实现Singleton模式.因此,它们不是同一件事(甚至是同一事物),但它们是相关的.

Singletons are a design pattern. Statics are Java language feature that can be used to implement the Singleton pattern. So they are not the same thing (or even the same kind of thing), but they are related.

这篇关于单例方法是否适合访问/维护数据库和Internet连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-24 13:18