简体   繁体   中英

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.

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. but using c# i can't seem to do anything static in an interface.

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. Interface when used with Singleton is often just for unit testing purposes

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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