[英]What kind of pattern is this ('Provider')?
At work we are using a 'pattern' that I didn't really find in the GoF book (but that may be due to lack of competence in this matter, I just skimmed the patterns) and that I'm still doubting somewhat. 在工作中,我们使用的是一种我在GoF书中没有找到的“模式”(但这可能是由于在这个问题上缺乏能力,我只是略去了模式)而且我仍然在怀疑。
Say, if we have a multi-project solution containing a project DataAccess that manages, well, the data access. 比方说,如果我们有一个包含项目DataAccess的多项目解决方案,那么管理数据访问。 Then usually I see it having a structure like this:
然后通常我看到它有这样的结构:
Providers (Folder)
- DataAccessProvider.cs
Interfaces (Folder)
- IFileLoader.cs
Implementors (Folder)
- FileLoader.cs
Here, FileLoader
would be an internal
implementation of the interface IFileLoader
, and the provider looks like this: 这里,
FileLoader
将是IFileLoader
接口的internal
实现,提供者看起来像这样:
public static class DataAccessProvider
{
public static IFileLoader FileLoader
{
get { return new FileLoader(); }
}
}
What kind of design pattern is this (if any), and what are its real uses besides masking the specific implementation of the IFileLoader
interface? 这是什么样的设计模式(如果有的话),除了屏蔽
IFileLoader
接口的具体实现之外,它的真正用途是什么?
And secondly, is this really 'good style'? 其次,这真的是“好风格”吗? I wonder, for example, what happens if there are many calls like
我想知道,例如,如果有很多电话会发生什么
string content = DataAccessProvider.FileLoader.LoadContentFromFile("abc.txt");
This would call new FileLoader()
whenever it is used. 无论何时使用,都会调用
new FileLoader()
。 Isn't there a more elegant way to do a similar approach? 是不是有更优雅的方式来做类似的方法?
In this example the DataAccessProvider
is an example of a simple Factory Method (pattern). 在此示例中,
DataAccessProvider
是简单工厂方法(模式)的示例。 Normally you would have a method called GetFileLoader()
or CreateFileLoader()
instead of a Property version, but the result is the same. 通常你会有一个名为
GetFileLoader()
或CreateFileLoader()
而不是Property版本,但结果是一样的。
The purpose of returning the IFileProvider
instead of FileProvider
is for Dependency Inversion, this way one could write other types of FileProvider
and inject them into the application without needed to rework or recompile all of the object that depend on an IFileProvider
. 返回
IFileProvider
而不是FileProvider
的目的是用于依赖性反转,这样就可以编写其他类型的FileProvider
并将它们注入应用程序,而无需返工或重新编译依赖于IFileProvider
所有对象。 It's not about masking. 这不是掩蔽。
If one is concerned about how many instances of FileLoader
are created, then one could use the Singleton pattern for that object. 如果关注创建了多少个
FileLoader
实例,那么可以使用该对象的Singleton模式。 However, this is normally not an issue if the FileLoader
is a lightweight object, since the CLR garbage collector will take care of that automatically for you. 但是,如果
FileLoader
是一个轻量级对象,这通常不是问题,因为CLR垃圾收集器会自动为您处理。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.