views:

1257

answers:

9

In .NET 3.5, I'd like to create a singleton interface:

interface ISingleton <T>
{
  public static T Instance {get;}
}

Of course that doesn't work but is what I'd like. Any suggestions?

EDIT: I just want it to be known that all singeltons will have a static property named Instance of the class type. It is always there. An interface would be an explicit way to express this.

+10  A: 

An Interface can't, to my knowledge, be a Singleton since it doesn't actually exist. An Interface is a Contract that an implementation must follow. As such, the implementation can be a singleton, but the Interface can not.

Matthew Brubaker
I think the OP meant something different. I understand the following question: "How would an interface description for a singleton class look like in C#?"
0xA3
You can't specify a singleton class from an interface since an interface only specifies a contract that the implementing class can meet in any way it sees fit.
Matthew Brubaker
A: 

Besides that it does not work, as you state, how would you use this interface and an implementing class?

You might try with a Factory-style interface

interface ISingletonFactory<T>
{
    public T Instance {get;}
}

public class SingletonFactory: ISingletonFactory<Singleton>
{
    public Singleton Instance {get { return Singleton.Instance;}}
}

public class Singleton
{
    private Singleton foo;
    public static Singleton Instance { get { return foo; } }
}
devio
This is not an answer, why did you not use the add comment feature?
AnthonyWJones
just added the answer ;)
devio
A: 

Given the classic notion of OOP of Interface which defines it as a Contract between implementing classes, you can't add such a thing as a static method to it. If you could do, you would be ending in something more similar to an abstract class in wich you have a partial implementation of your class and other parts demanded to the extending classes.

Stefano Driussi
A: 

I just want it to be known that all singeltons will have a static property named Instance of the class type. It is always there. An interface would be an explicit way to express this.

4thSpace
but remember that a singleton is a Design Pattern, not a strict directive. You're always free to implement it the way you like unless you change it's behaviour.
Stefano Driussi
Excellent point. Even if you did provide a property that would return an instance that implemented the Interface, there's no guarantee that it would be a singleton.
Matthew Brubaker
@4thspace - I edited your question with the additional data you provide here. This is not an answer, and should be deleted. That's how SO is supposed to work.
Sunny
voted down so he'd delete it :) (delete it and the down vote goes away)
jcollum
+2  A: 

I just want it to be known that all singeltons will have a static property named Instance of the class type. It is always there. An interface would be an explicit way to express this.

Write a unit test instead.

Justice
A: 

As pointed out, you can't do this and there are good reasons why you shouldn't.

The method I've implemented in the past creates a interface and an abstract base class that implements the interface. It looks something like this:

public interface IMyCompanySetting
{
 XmlNode Serialize();
 IMyCompanySetting Deserialize(XmlNode pattern);
 string SettingName { get; }

string Key { get; } object SettingValue { get; set; } SettingScope Scope { get; set; } }

public abstract class MyCompanySettingBase : IMyCompanySetting
{
 public MyCompanySettingBase() {}
 public MyCompanySettingBase(XmlNode pattern)
 {
  Deserialize(pattern);
 }
 #region IMyCompanySetting Members

 public abstract XmlNode Serialize();
 public abstract IMyCompanySetting Deserialize(XmlNode pattern);
 public abstract string SettingName{ get; }
public abstract string Key { get; }
 public abstract SettingScope Scope{ get; set; }
 public abstract object SettingValue{ get; set; }

 #endregion

public static XmlNode WrapInSettingEnvelope(XmlNode innerNode, IMyCompanySetting theSetting)
{
    // Write the top of the envelope.
    XmlTextWriter xtw = null;
    MemoryStream theStream = OpenSettingEnvelope(theSetting, ref xtw);

    // Insert the message.
    xtw.WriteNode(new XmlTextReader(innerNode.OuterXml, XmlNodeType.Element, null), true);

    // Close the envelope.
    XmlNode retNode = CloseSettingEnvelope(xtw, theStream);
    return retNode;

}

public static MemoryStream OpenSettingEnvelope(IMyCompanySetting theSetting, ref XmlTextWriter theWriter)
{
    MemoryStream theStream = new MemoryStream();
    theWriter = new XmlTextWriter(theStream, Encoding.ASCII);
    System.Type messageType = theSetting.GetType();

    string[] fullAssembly = messageType.Assembly.ToString().Split(',');
    string assemblyName = fullAssembly[0].Trim();

    theWriter.WriteStartElement(theSetting.SettingName);
    theWriter.WriteAttributeString("type", messageType.ToString());
    theWriter.WriteAttributeString("assembly", assemblyName);
    theWriter.WriteAttributeString("scope", ConfigurationManager.ScopeName(theSetting.Scope));

    return theStream;
}

public static XmlNode CloseSettingEnvelope(XmlTextWriter xtw, MemoryStream theStream)
{
    XmlDocument retDoc = new XmlDocument();
    try
    {
        // Close the envelope.
        xtw.WriteEndElement();
        xtw.Flush();

        // Return the node.
        string xmlString = Encoding.ASCII.GetString(theStream.ToArray());
        retDoc.LoadXml(xmlString);
    }
    catch (XmlException)
    {
        string xmlString = Encoding.ASCII.GetString(theStream.ToArray());
        Trace.WriteLine(xmlString);
        retDoc.LoadXml(@"<error/>");
    }
    catch (Exception)
    {
        retDoc.LoadXml(@"<error/>");
    }
    return retDoc.DocumentElement;
}

}
Jekke
+2  A: 

Ok I made this answer a Wiki, because I am just going to offer an opinion that is at a tangent to your question.

I personally think that Singletons are waaay overused, its a use case that IMO is actually reasonably rare, in most cases a static class would suit the use case much better, and in other cases just a factory created imutable object is the best choice, an actual singleton is much rarer than people think.

I wouldn't have an interface to describe a common pattern for this, as I would actually want each and every use of a singleton to be thought about very carefully and justified.

Tim Jarvis
+1  A: 

I know it's not your question, but how many singletons do you have such that you require an interface? This smells like bad design to me - can you explain clearly why these classes should be singletons rather than instances? If your answer is memory, I would suggest your overthinking your application, and if you're really concerned, look into the flyweight pattern (or perhaps a simple factory pattern). Sorry for not answering the question directly, but this doesn't sound like a great idea.

Travis
+3  A: 

While I agree with other posters that singletons are very much over used, a possible solution to your question is to provide an abstract base class with a type parameter of the derived singleton:

public abstract class Singleton<T> where T : Singleton<T>
{
  private static T _instance;

  public static T Instance
  {
    get { return _instance; }
    protected set { _instance = value; }
  }
}

Any class that derives from Singleton will have a static Instance property of the correct type:

public class MySingleton : Singleton<MySingleton>
{
    static MySingleton()
    {
        Instance = new MySingleton();
    }

    private MySingleton() { } 
}

Before using something like this though you should really think about whether a singleton is required or if you are better off with a normal static class.

Andrew Kennan