how to apply dependency injection in an inventory management system
i want to implement a sales aand inventory management system, am confused as to how to apply dependency injection in the system. I want to have an inventory class that uses database to persist its data, should i have a class that handles the database connection say DBConnectionManager, then a database layer DBWrapper that uses DBConnectionManager and interacts with the DB, then acts as an abstract layer between the DB and classes that use the DB such as Inv开发者_Go百科entory, Users, Customers, Sales. Or should i write sql codes in each User, Customer, .... Class.
Have youi tryed the Repository Pattern ?
It's great to use with DI, you build a root class that holds connections and basic operations like Update, remove etc...
And then extend that class to create more specific behaviours with more meaningful names...
Here is the a link about it
http://nhibernate.hibernatingrhinos.com/27/the-repository-pattern
IMO, you should have a DAO interface created for your db activities/operations. This DAO interface will have generic operations for storing/retrieving data. You can then have classes implement this DAO interface; one class would enabled database persistence, one class would enabled text file based persistence (in case you need one) etc.
Your database implementation DAO would in turn have a java.sql.Connection
reference which will enable it to connect to a database. You'll use a dependency mechanism (like Spring or Guice) to inject appropriate instances at runtime for both DAO interfaces and connection objects.
Basically, learn to think in terms of interfaces and prefer composition over inheritance (and don't shy away from using inheritance to avoid code duplication; just make sure the super-class doesn't form a part of the contract or isn't exposed to the outside world. I've personally found Google Guice docs a good source of how to start thinking in terms of modules (in the context of dependency injection).
精彩评论