Skip to main content
 首页 » 编程设计

c#之双例模式实现

2024年02月24日29birdshome

我正在利用 the Doubleton Design Pattern on Code Project 中的 Doubleton 模式在我自己的代码中。我认为它使事情变得容易得多,因为 Singleton 只提供一个实例,但我用这种模式得到了两个。我想知道让它实现一个接口(interface)是否有意义,以便我可以将它注入(inject)我的领域层。

请您参考如下方法:

尽管这样的设计很有用和聪明,但这是不可能的。您不能在接口(interface)中定义静态成员。

public interface IDoubleton 
{ 
    static IDoubleton Instance { get; } // Can't be done 
} 

@Pierreten,如果你使用实例方法,想象一下:

IDoubleton firstInstance; 
// Construct firstInstance, 
// do some stuff... 
 
// Now comes trouble. 
IDoubleton secondInstance = firstInstance.Instance; // what does it mean? 
IDoubleton anotherInstance = secondInstance.Instance.Instance.Instance; // what now? 

编辑:正如@Roger Pate 正确指出的那样,我的第二个答案应该合并到这个答案中。因为他已经做了,所以我删除了另一个。