我开始考虑在未来的项目或重构中实现控制反转容器,我想知道在正确设计依赖关系时,哪些原则(除了 GoF 模式)可能值得记住。假设我需要构建一个简单的控制台应用程序,如果它可以访问互联网,它将在 Amazon 中搜索一本书(按 ISBN),或者在没有可用连接时回退到本地数据库(SQLite、SqlServerCE)。因此,最初的设计可能几乎是:
- IAmazonSearchProvider
- ILocalSearchProvider
- IResultsGenerator (取决于 IAmazonSearchProvider 或 ILocalSearchProvider)
- IOutputFormatter
- ConsoleApplication (取决于 IOutputFormatter)
任何指导都将非常感激,非常感谢。
I'm starting to consider implementing Inversion of Control containers in my future projects or refactorings and I was wondering which principles (besides GoF patterns) might be interesting to keep in mind when it comes to properly design dependencies. Say I need to architect a simple console app that will search for a book (by ISBN) in Amazon if it can access the internet or will fallback to a local database (SQLite, SqlServerCE) when there is no connection available. So the initial design might pretty much be:
- IAmazonSearchProvider
- ILocalSearchProvider
- IResultsGenerator (depending on either IAmazonSearchProvider or ILocalSearchProvider)
- IOutputFormatter
- ConsoleApplication (depends on IOutputFormatter)
Any guidance will be really appreciated, thanks a lot in advance.
发布评论
评论(2)
这是一种非常正常的方法,而且还不错,但它主要关注机制,并且可能会带来违反 重用抽象原则。从较高的层面来看,如果您可以让 API 描述它的作用,而不是它的作用方式,那么您的情况会更好。遵循好莱坞原则是一个重要的开始。
在设计抽象时,优先考虑组合而不是继承。除此之外,优先选择角色接口而不是标头接口。
目前,我使用 角色接口方法的松散排名,如下所示(其中 命令是best):
That's a pretty normal approach, and it's not bad, but it focuses much on mechanics and may entail the risk of violating the Reused Abstractions Principle. At a high level, you'd be better off if you can make the API describe what it does instead of how it does it. Following the Hollywood Principle is an important start.
When designing abstractions, favor composition over inheritance. Apart from that, favor Role Interfaces over Header Interfaces.
Currently, I work with a loose ranking of Role Interface methods like this (where Commands are best):
我假设
I*
是接口。IResultsGenerator
和ILocalSearchProvider
听起来像是IResultsGenerator
的实现(因此不是接口)。还有一些东西应该依赖于IResultsGenerator
,我推荐它是ConsoleApplication
。其余的看起来都不错。
I assume
I*
are interfaces.IResultsGenerator
andILocalSearchProvider
sounds like implementations (and so not interfaces) ofIResultsGenerator
. Also something should depend onIResultsGenerator
, I recommend it'sConsoleApplication
.The rest looks fine.