Singleton Design Pattern Realtime Example of banking


Logger Utility in a Banking System using Singleton

In a banking application, you might have a logger that logs important events like transactions, errors, and user activities. You want to ensure that only one instance of the logger exists throughout the application to maintain a consistent log format and avoid file access conflicts.

1) Why Singleton? A logging class doesn't need multiple instances. One instance is sufficient and more efficient.

2) Consistency: All log messages are centralized through one instance.

4) Resource Management: Avoids file access conflicts and redundant memory usage.


using System;

public sealed class Logger

{

    private static Logger instance;

    // Private constructor to prevent instantiation from outside

    private Logger()    {

        Console.WriteLine("Logger Initialized.");

    }

    // Public method to get the single instance

    public static Logger GetInstance()

    {

        if (instance == null)

        {

            Console.WriteLine("Creating Logger Instance...");

            instance = new Logger();

        }

        return instance;

    }

    // Example method to simulate logging

    public void Log(string message)

    {

        Console.WriteLine("[LOG] " + message);

    }

    public static void Main(string[] args)

    {

        // Simulate two users performing transactions

        Logger logger1 = Logger.GetInstance();

        logger1.Log("User1 deposited 500.");


        Logger logger2 = Logger.GetInstance();

        logger2.Log("User2 withdrew 200.");

        // Confirm both logger1 and logger2 refer to the same instance

        Console.WriteLine("Are both loggers same instance? " + (logger1 == logger2));

    }

}

-



Comments

Popular posts from this blog

API development using .NET Core - ProductManagmentCRUD

Consume API in MVC Application