如何在库存管理系统中应用依赖注入
我想实现一个销售和库存管理系统,但对如何在系统中应用依赖注入感到困惑。我想要一个使用数据库来保存其数据的库存类,我应该有一个处理数据库连接的类,比如 DBConnectionManager,然后是一个使用 DBConnectionManager 并与数据库交互的数据库层 DBWrapper,然后充当数据库之间的抽象层DB 和使用 DB 的类,例如库存、用户、客户、销售。或者我应该在每个用户、客户、...类中编写sql代码。
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 Inventory, Users, Customers, Sales. Or should i write sql codes in each User, Customer, .... Class.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您尝试过存储库模式吗?
与 DI 一起使用非常棒,您可以构建一个根类来保存连接和更新、删除等基本操作...
然后扩展该类以使用更有意义的名称创建更具体的行为...
这是有关它的链接
http://nhibernate.hibernatingrhinos.com/27/the-repository-pattern
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,您应该为您的数据库活动/操作创建一个 DAO 接口。该 DAO 接口将具有用于存储/检索数据的通用操作。然后你可以让类实现这个 DAO 接口;一个类将启用数据库持久性,一个类将启用基于文本文件的持久性(如果您需要的话)等。
您的数据库实现 DAO 反过来将具有一个
java.sql.Connection
引用来启用它连接到数据库。您将使用依赖机制(如 Spring 或 Guice)在运行时为 DAO 接口和连接对象注入适当的实例。基本上,学会从接口的角度思考,并且更喜欢组合而不是继承(并且不要回避使用继承来避免代码重复;只需确保超类不构成契约的一部分或不公开我个人发现谷歌指南文档是如何开始从模块角度思考(在依赖注入的上下文中)的一个很好的来源。
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).