简体   繁体   中英

What is difference between using singleton class and class with static methods?

what is need of singleton(state is fixed ) class if 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

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