As I go through the differences between Singleton Vs Static class, I came across one point that we can inherit an interface in singleton class and can call singleton through interface for multiple implementation.
What exactly mean we can call singleton through interface for multiple implementation, please suggest some code demonstration with some good real time example.
Here I m also using logging through below, but what exactly mean for multiple implementation?
class Program { static void Main(string[] args) { ILogger logger = Logger.GetLogger(); logger.LogMessage("Hello"); } } public interface ILogger { void LogMessage(string message); } public class Logger : ILogger { private static Logger instance; public static Logger GetLogger() { return instance ?? (instance = new Logger()); } public void LogMessage(string message) { Console.WriteLine(message); } }
theLizardPosted Mar 14, 2014, 6:37 PM
If you write applications without a Singleton, then you would be able to run your application multiple times at the same time.
With a Singleton, if you tried to open another instance of the application, the new instance should shut down and set focus to the existing Singleton object (application).
There are many reasons why you would only ever want to run a single(ton) instance
VulpesPosted Mar 14, 2014, 3:41 PM
However, you can implement one or more interfaces and this is sometimes used as a way to simulate multiple inheritance.
Possibly, the phrase: "can call singleton through interface for multiple implementation" is alluding to this possibility as the singleton could inherit from a class and implement an interface at the same time.
This wouldn't be possible with a static class which can't implement an interface and can only inherit from the System.Object class.