DEV Community

Cover image for Cooperation between Singleton and Factory with Example
Islam nabil
Islam nabil

Posted on

Cooperation between Singleton and Factory with Example

Connection between Singleton and Factory Design Patterns
In software engineering, design models are useful tools that help solve common design problems efficiently and reusable. In these models, Singleton and Factory models are commonly used and can be combined to provide a powerful scheduling solution. In this article, we will look at how these two models can work together, with practical explanations and examples.

Singleton

Singleton patterning ensures that there is only one instance of a particular class throughout the lifecycle of the application. This option is used when access to a shared resource, such as a database link or shared file, needs to be controlled. This is done by creating and storing a single instance of the class so that it can be accessed whenever the application needs to access that object.

Factory

The factory pattern creates objects without specifying the exact class to be instantiated. This model allows users to create content without relying on a specific class, add more features and easily use the application.

Cooperation between Singleton and Factory

Combining the Singleton and Factory instances, we can use the Singleton to identify the Factory itself as a single instance, which means that all objects created by the Factory come from the same source. This integration is ideal for applications that need to manage volumes or use limited resources.

An example of what can be done
Let’s assume we’re working with a multimedia application. We need to make sure we have at least one relationship with us.

// Singleton Pattern: DatabaseConnection
public class DatabaseConnection
{
    private static DatabaseConnection _instance;
    private string _connectionString;

    private DatabaseConnection(string connectionString)
    {
        _connectionString = connectionString;
    }

    public static DatabaseConnection GetInstance(string connectionString)
    {
        if (_instance == null)
        {
            _instance = new DatabaseConnection(connectionString);
        }
        return _instance;
    }

    public string GetConnectionString()
    {
        return _connectionString;
    }
}

// Factory Pattern: DatabaseFactory
public class DatabaseFactory
{
    private static DatabaseFactory _factoryInstance;

    private DatabaseFactory() { }

    public static DatabaseFactory GetFactoryInstance()
    {
        if (_factoryInstance == null)
        {
            _factoryInstance = new DatabaseFactory();
        }
        return _factoryInstance;
    }

    public DatabaseConnection CreateConnection(string dbType)
    {
        if (dbType == "SQL")
        {
            return DatabaseConnection.GetInstance("SQL Connection String");
        }
        else if (dbType == "NoSQL")
        {
            return DatabaseConnection.GetInstance("NoSQL Connection String");
        }
        else
        {
            throw new ArgumentException("Unknown database type");
        }
    }
}

// Usage Example
class Program
{
    static void Main()
    {
        // Get the factory instance (Singleton)
        var factory = DatabaseFactory.GetFactoryInstance();

        // Create a SQL connection (Singleton)
        var sqlConnection = factory.CreateConnection("SQL");
        Console.WriteLine(sqlConnection.GetConnectionString());

        // Create a NoSQL connection (this will still return the SQL connection due to Singleton)
        var nosqlConnection = factory.CreateConnection("NoSQL");
        Console.WriteLine(nosqlConnection.GetConnectionString());
    }
}

Enter fullscreen mode Exit fullscreen mode

Explanation of the Example:

Singleton Pattern:

DatabaseConnection ensures that there's the most effective connection to the database. Even if we try to create a brand new connection with a different database type, the same instance is returned.

Factory Pattern:

DatabaseFactory** makes use of Singleton to make sure that there is the handiest manufacturing facility instance. The manufacturing facility can create database connections based on their type.

Collaboration Between the Two Patterns:

When we strive to create a connection with "NoSQL", DatabaseFactory tries to use DatabaseConnection to create a brand new connection. However, because DatabaseConnection follows the Singleton pattern, it returns the primary created instance, making sure that there is only one database connection during the application's lifetime.

Conclusion

The collaboration among layout patterns like Singleton and Factory can be a powerful manner to manipulate resources in huge applications. The Singleton pattern can manage the quantity of created gadgets, even as the Factory sample offers flexibility in developing those items. Together, they provide a robust and maintainable software architecture.

Top comments (0)