我正在尝试规划将 MySQL 连接代码放在哪里 -
MCPConnection *conn = [[MCPConnection alloc] initToHost:@"" withLogin:@"" usingPort:@""];
等Mac 上的 MCPKit。我的目标是在整个应用程序中创建尽可能少的连接实例(如果可能的话,只有一个就很棒了)。
我能想到的唯一 3 个地方是 -
-
应用程序委托,但是我如何在其他类中使用相同的连接(数据封装)
-
将代码放置在每个需要它来实现每个单独目的的窗口/视图控制器中(但这意味着更多的代码和大量的连接,这是我不想要的) .
-
或者最终为所有 MySQL 查询和单个连接设置一个单独的类。 (但是如何做到这一点,以便该类中的方法可以轻松调用,或者使 SQL 语句/查询能够足够适应使用这些方法的每个其他类)。
我希望这不会太令人困惑 - 要点是 - 我在哪里放置连接代码,它是否可以在类之间很好地承载,或者是否需要在应用程序的使用过程中单独并连续调用它。
感谢您抽出时间。
I am trying to plan out where to put my MySQL connection code -
MCPConnection *conn = [[MCPConnection alloc] initToHost:@"" withLogin:@"" usingPort:@""];
etc. from MCPKit on the mac. My aim is to make as few connection instances as possible through the whole app (if possible just one will be awesome).
The only 3 places i can think of putting it are -
-
The app delegate, but then how would I use the same connection in other classes (data encapsulation)
-
Place code in Each and every Window/View controller that requires it to fulfil each individual purpose (but this means a lot more code and a large number of connections which i do no want).
-
Or finally setting up an individual class for all the the MySQL queries and a singular connection. (but then how to do that so that the methods in this class are easily callable, or so that the SQL statements/queries can be adaptive enough for every other class that uses the methods).
i hope that hasn't been too confusing - the main point is this - where do i put the connection code, does it carry between classes well, or does it need to be called individually and successively throughout use of the app.
Thank you for your time.
发布评论
评论(1)
作为一个简单的解决方案,您可以使用 Singleton 模式并用对静态 getInstance 的调用替换 init 代码。单例包装器的唯一公共方法是 getConnection,然后您可以像平常一样使用它。是的,您可以将常见的 sql 构建方法拉入该类中,但这会导致代码膨胀,最好对单独类型的查询使用享元模式。
这种设计的唯一缺点是对单个共享数据库连接的访问必须始终进行序列化,如果有多个同时访问数据库的线程,这可能会使您的某些 UI 变慢且无响应。
As a simple solution, you can use Singleton pattern and replace init code with call to static getInstance. The only public method of singleton wrapper would be getConnection, which then you use as normal. Yep, you can pull common sql-building methods into that class, but that leads to code bloat, better use Flyweight pattern for separate-type queries.
The only drawback of such design is that access to that single shared database connection must always be serialized, which may render some your UI slow and irresponsive if there are multiple simultaneous threads accessing database.