Applying Creational Patterns in a Banking System

Applying Creational Patterns in Banking System

You've learned so much about creational patterns, and it's time to apply what you know to a real-world project: a banking system. In this unit, we'll focus on using creational patterns to manage and simplify the creation of banking system components.

Quick Pattern Refresher

Before we dive in, let's quickly recap the creational patterns we'll use:

  1. Singleton Pattern: Ensures a class has only one instance and provides a global point of access to it.
  2. Factory Method Pattern: Defines an interface for creating an object but allows subclasses to alter the type of objects that will be created.
  3. Abstract Factory Pattern: Provides an interface for creating families of related or dependent objects without specifying their concrete classes.
  4. Builder Pattern: Separates the construction of a complex object from its representation, allowing the same construction process to create various representations.

We will implement these patterns to create a logger, accounts, and account factories for our banking system.

What You'll Build

Let's see what you'll build in this unit. You will create:

  1. Logger with the Singleton Pattern: A logging mechanism that ensures only one instance of the logger exists throughout the application using Lazy<Logger>.
  2. Accounts using the Factory Method Pattern: Different types of accounts (SavingsAccount and CurrentAccount) created via a factory method.
  3. Account Factories using the Abstract Factory Pattern: Factories that will instantiate different types of accounts.
  4. Code Integration: Comprehensive integration of these patterns into a cohesive system.

Singleton Pattern for Logger

First, let's create a logger using the Singleton Pattern. This will ensure that there is only one instance of the logger throughout the application.

C#
// Sealed Logger class, preventing inheritance
public sealed class Logger
{
    // Private constructor to restrict instantiation
    private Logger() { }

    // Static variable for holding the singleton instance
    private static readonly Lazy<Logger> instance = new Lazy<Logger>(() => new Logger());

    // Public static method to retrieve the singleton instance
    public static Logger Instance => instance.Value;

    // Public method to log a message to the console
    public void Log(string message)
    {
        Console.WriteLine(message);
    }
}

Here, the Logger class ensures that only one instance of the logger exists. The Lazy<Logger> type provides thread-safe lazy initialization, and the Instance property is used to access the single instance. Whenever a message needs to be logged, the single instance is used.

Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal