我想创建一个灵活的类,因此我可以切换实现。
问题:存储文件/文档
选项:在服务器文件系统、数据库等本地存储。
有人可以帮忙介绍一下类(class)的骨架结构吗?我怎么称呼它?
我没有使用 IoC,也不想使用。我只想要在工厂中进行 1 次代码更改以调用另一个实现的灵 active 。
最佳答案
使用接口(interface)。
interface IStorage
{
void Save(string filename);
}
然后创建您的各种实现:
class LocalStorage : IStorage
{
void Save(string filename)
{
-implementation code-
}
}
然后,在你的消费类
IStorage storage = new LocalStorage();
// uses local storage
storage.Save();
storage = new DatabaseStorage();
// now use database storage
storage.Save();
关于c# - 使用构造函数依赖注入(inject)检索文件的简单工厂,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1924129/