我正在利用 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 正确指出的那样,我的第二个答案应该合并到这个答案中。因为他已经做了,所以我删除了另一个。
关于c# - 双例模式实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3026282/