简体   繁体   English

在C#中将Singleton模式与接口一起使用

[英]Using the Singleton pattern with an interface in C#

Note: Even though there are a lot of similar questions, non that i have found answered my question. 注意:即使有很多类似的问题,我都没有找到答案。

Problem: I would like to implement a class in C# which uses the singleton pattern in the following way. 问题:我想在C#中实现一个类,该类以以下方式使用单例模式。

namespace DAL
{
    public class CDAL : IDAL
    {
        /* Singleton Pattern */
        private CDAL instance = null;
        private CDAL()
        {
        }
        public IDAL getInstance()
        {
            if (instance != null)
            {
                return instance;
            }
            else
            {
                CDAL.instance = new CDAL();
                return CDAL.instance;
            }
        }
    }

}

the problem is that instance and the method getInstance should be static , as i want to 'ask' the class for that instance and not an object. 问题是实例和方法getInstance应该是静态的 ,因为我想“询问”该实例的类而不是对象。 but using c# i can't seem to do anything static in an interface. 但是使用c#我似乎无法在接口中执行任何静态操作。

how can i solve this? 我该如何解决?

You're right, you cannot do anything static on an interface, since it does not make any sense. 没错,您不能在接口上执行任何静态操作,因为这没有任何意义。 Use an abstract class instead of the interface to implement static logic. 使用抽象类而不是接口来实现静态逻辑。

It does not make any sense creating an interface with a static member. 用静态成员创建接口没有任何意义。 Interfaces are a contract while the static member is always accessed by the class name, not the instance name. 接口是一种约定,而静态成员始终通过类名而不是实例名访问。 so briefly your interface does not know which the correct instance implementing the right logic. 因此,简短地说,您的界面不知道哪个正确的实例实现了正确的逻辑。 in your case you don't need your method getInstance() to be defined in the interface. 在您的情况下,不需要在接口中定义方法getInstance() Interface when used with Singleton is often just for unit testing purposes Singleton使用时,界面通常仅用于unit testing

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM