Results 1 to 9 of 9
May 2, 2013, 15:44 #1
- Join Date
- Dec 2003
- 7 Post(s)
- 0 Thread(s)
Sharing database object without singleton
Realizing that singletons are not good for writing testable code I have done some reading and found out that a much better pattern is dependency injection. I've seen some code samples that looked logical but they didn't involve the case of a database object, which basically I need to have only one instance of in my whole application.
So far I have come to this conclusion if an object of class A is dependent on an object of class B:
1. Class A should require object B in the constructor.
2. The code that uses object A uses a factory to create object A so that it is not involved in the complexities of instantiating
3. The factory instantiates object B and passes it to the constructor of object A and returns object A.
The problem with that is that the factory is not a singleton so it creates a new instance of classes each time. So if B is our database class that A depends on, then the factory will create a new instance of the database object each time it is called - unless it uses a singleton.
Does that mean that DI and Factory cannot be used to solve the problem? From what I have read the proper use of DI prevents me from having to pass objects down all the layers in my application just because one method somewhere deep needs it - but I can't see how this can work for objects that really need to have only one instance like database connection. Am I doomed to passing Db around from one object to another multiple times or can I achieve it in an elegant way without using statics?