What is difference between using singleton class and class with static methods?
what is need of singleton(state is fixed ) class i开发者_开发问答f I have class with static methods (fixed behaviors )?
With the singleton it is easier to replace the instance if needed, for example, for testing.
I think one of the best arguments for using a singleton rather than a class with purely static methods is that it makes it easier to introduce multiple instances if this turns out to be required later. It is not uncommon to see applications where there is no fundamental reason to restrict a class to a single instance, but the authors did not envision any extension of their code, and found it easier to use static methods. Then when you want to extend the application later it is much harder to do so.
Being able to replace the instance for testing (or other reasons) is also a good point, and being able to implement an interface also helps with this.
Well following article is in C# but i think this also same for teh java have look to it may help you to understand
Use singletons with interfaces
You can use singletons with interfaces just like any other class. In C#, an interface is a contract, and objects that have an interface must meet all of the requirements of that interface.
Singletons can used with interface
/// <summary>
/// Stores signatures of various important methods related to the site.
/// </summary>
public interface ISiteInterface
{
};
/// <summary>
/// Skeleton of the singleton that inherits the interface.
/// </summary>
class SiteStructure : ISiteInterface
{
// Implements all ISiteInterface methods.
// [omitted]
}
/// <summary>
/// Here is an example class where we use a singleton with the interface.
/// </summary>
class TestClass
{
/// <summary>
/// Sample.
/// </summary>
public TestClass()
{
// Send singleton object to any function that can take its interface.
SiteStructure site = SiteStructure.Instance;
CustomMethod((ISiteInterface)site);
}
/// <summary>
/// Receives a singleton that adheres to the ISiteInterface interface.
/// </summary>
private void CustomMethod(ISiteInterface interfaceObject)
{
// Use the singleton by its interface.
}
}
Here we can use the singleton on any method that accepts the interface. We don't need to rewrite anything over and over again. These are object-oriented programming best practices. You can find more detailed examples on the interface type in the C# language here.
C# Singleton Pattern Versus Static Class
精彩评论