简体   繁体   English

我应该使用单例,静态类还是“共享”从多个类连接到数据库?

[英]Should I use singleton, static Class or `shared` for connecting to database from many classes?

I am writing Apps that connect to DB. 我正在编写连接数据库的应用程序。 I need be able use DataBase connection from many classes. 我需要能够使用许多类的数据库连接。

class Database
{
  auto MyConnection = new Connection("..."); // create connection

  void calc()
  {
    MyConnection.query("..."); // use it
  }
}

But I need to get access to MyConnection from every class? 但是我需要从每个班级访问MyConnection吗? Should I do Database class static ? 我应该使Databasestatic吗? Or maybe I should use Singleton patter? 还是我应该使用Singleton模式? Or make MyConnection as shared ? 还是将MyConnection设为shared

And for example what about config? 例如配置呢? Is it's good idea to make it for example shared ? 是它的好主意,使其例如shared

Or for example can I declare connection statement globally before main? 还是例如可以在main之前全局声明连接语句? Like: 喜欢:

MySQLPool MyConnection;

void main()
{
//...
}

and then initiate MyConnection from static this() { } or from DB class? 然后从static this() { }或从DB类启动MyConnection

Have a look at the Repository pattern as described here: http://web.archive.org/web/20150404154203/https://www.remondo.net/repository-pattern-example-csharp/ 看看这里描述的Repository模式: http : //web.archive.org/web/20150404154203/https : //www.remondo.net/repository-pattern-example-csharp/

You should be thinking about the architecture of your application. 您应该考虑应用程序的体系结构。 I you go with this approach then I would have a class called db (not static and not singleton) with methods like: 我采用这种方法,那么我将得到一个名为db的类(不是静态的也不是单例的),其方法如下:

Read
Scaler
Execute
Insert
etc 

Your repository layer should be separate to your domain layer. 您的存储库层应与域层分开。

In my experience this makes the code testable. 以我的经验,这使代码可测试。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM