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

what is needed for a singleton (state is fixed) class if I have a class with static methods (fixed behavior)?

+3
source share
3 answers

Using singleton is easier to replace an instance if necessary, for example, for testing.

+2
source

, singleton, , , , . , , - , . , , .

( ) , .

+1

, #, , java, ,

You can use singleletons with interfaces, like any other class. In C #, an interface is a contract, and objects that have an interface must satisfy all the requirements of that interface.

Singlets can be used with the 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 singleton for any method that accepts an interface. We do not need to rewrite anything again and again. This is best practice for object-oriented programming. Below you can find more detailed examples on the type of interface in C #.

C # Singleton Pattern Versus Static Class

0
source

All Articles