我有一个基本的设计问题,我一直找不到一个好的答案(在这里,在其他论坛上,也没有我查阅过的书籍)。
我正在创建一个dll,并想知道公开其内容的最佳方法是什么。我的目标是一个单一的入口点的应用程序使用dll。
解决方案应遵循依赖反转原则(DIP),这将意味着使用接口。但是这里有一个问题: dll的功能要求一个对象被实例化,而且在任何时候都必须只有几乎一个实例(有点像一个人,尽管这种想法会让我的脊柱颤抖)--这就是我想让DLL的用户不知道的事实。
一些代码来解释我想要做的事情:
dll:
namespace MyQuestionableDll
{
interface IMyQuestionableDll
{
public static IMyQuestionableDll Instance; // This is not allowed which makes sense
public void PressTheRedButton();
}
internal class QuestionableImplementation : IMyQuestionableDll
{
public void PressTheRedButton()
{
// Distribute Norwegian Black Metal at local school
}
}
}以及用例:
using MyQuestionableDll;
class UnluckyAppThatIsForcedToUseQuestionableDlls
{
static void Main(string[] args)
{
IMyQuestionableDll questionableInstance = IMyQuestionableDll.Instance; // Again not allowed which still makes sense
questionableInstance.PressTheRedButton();
// or simply
MyQuestionableDll.Instance.PressTheRedButton();
}
}一个抽象的类可能是答案的一部分,但随后它开始感觉不再跟随探底了。
有什么伟大的设计洞察力,最佳实践知识时,制定dll或建议挪威黑色金属?
如果解释太含糊,我很乐意详细说明。
干杯!-雅各布
发布于 2022-01-27 12:30:35
我可以想象出一个双因素的方法:
例如:
public interface IMyApiFactory
{
IMyAPI GetInstance();
}
public interface IMyAPI
{
// Whatever your API provides
}这样,您就可以在dll中完全控制如何创建和重用实例(或不创建实例)。
类似的方法可能是某种Builder模式:
public interface IMyApiBuilder
{
IMyApi Build();
}
public interface IMyApi
{
void PressTheRedButton();
// Whatever it does else
}
public sealed class MyAPI : IMyApi, IMyApiBuilder
{
public static IMyApiBuilder Builder = new MyAPI();
private MyAPI()
{
// CTOR ...
}
// vv Notice _explicit_ interface implemenations.
// https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/interfaces/explicit-interface-implementation
IMyApi IMyApiBuilder.Build() { return this; }
void IMyApi.PressTheRedButton()
{
// ...
}
}
// USAGE:
IMyApi api = MyAPI.Builder.Build();发布于 2022-01-31 12:53:02
非常感谢Fildor和ema!添加一个工厂方法,一个要素界面,甚至是一个成熟的建设者的想法,绝对是很好的解决方案!它让我思考如何将它们合并到我的DLL中,同时还保留了它的用户。他们不需要知道,它实际上是一个恶臭的工厂,有污染的烟囱排放物,造成了这样的情况:)
然后,我遇到了默认的接口方法,我的方法的结构最终是
public interface MyQuestionableDll
{
static readonly MyQuestionableDll Instance = new QuestionableImplementation();
void PressTheRedButtonBelowTheDoNotPushSign();
}
internal class QuestionableImplementation : MyQuestionableDll
{
public void PressTheRedButtonBelowTheDoNotPushSign()
{
// Distribute German Volksmusik at local school
}
}
// and the use case
var questionableInstance = MyQuestionableDll.Instance;
questionableInstance.PressTheRedButtonBelowTheDoNotPushSign();再次感谢Fildor和ema!
https://stackoverflow.com/questions/70878402
复制相似问题