Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts

Monday, September 29, 2025

🏭 Factory Design Pattern in C# with Real-Time Example

📌 What is the Factory Design Pattern?

The Factory Design Pattern is a creational pattern used in object-oriented programming to abstract the process of object creation. Instead of instantiating classes directly using new, the Factory Pattern provides a method that returns instances of different classes based on input parameters.

This pattern is especially useful when:

  • The exact type of object to create is determined at runtime.
  • You want to encapsulate object creation logic.
  • You need to adhere to the Open/Closed Principle (open for extension, closed for modification).

🚗 Real-Time Example: Vehicle Factory in C#

Imagine you're building a transportation management system that handles different types of vehicles: Car, Bike, and Truck. Each vehicle has its own behavior, but the client code shouldn't worry about how these objects are created.

✅ Step-by-Step Implementation

1. Define a Common Interface

public interface IVehicle
{
    void Start();
}

2. Create Concrete Implementations

public class Car : IVehicle
{
    public void Start()
    {
        Console.WriteLine("Car started.");
    }
}

public class Bike : IVehicle
{
    public void Start()
    {
        Console.WriteLine("Bike started.");
    }
}

public class Truck : IVehicle
{
    public void Start()
    {
        Console.WriteLine("Truck started.");
    }
}

3. Implement the Factory Class

public static class VehicleFactory
{
    public static IVehicle GetVehicle(string vehicleType)
    {
        switch (vehicleType.ToLower())
        {
            case "car":
                return new Car();
            case "bike":
                return new Bike();
            case "truck":
                return new Truck();
            default:
                throw new ArgumentException("Invalid vehicle type");
        }
    }
}

4. Client Code

class Program
{
    static void Main(string[] args)
    {
        IVehicle vehicle1 = VehicleFactory.GetVehicle("car");
        vehicle1.Start();

        IVehicle vehicle2 = VehicleFactory.GetVehicle("bike");
        vehicle2.Start();
    }
}

🎯 Benefits of Using Factory Pattern in C#

  • Encapsulation: Object creation logic is hidden from the client.
  • Scalability: Easily add new vehicle types without changing client code.
  • Maintainability: Centralized object creation makes debugging and updates easier.
  • Loose Coupling: Promotes interface-based programming.

📝 Final Thoughts

The Factory Design Pattern is a cornerstone of clean, scalable software architecture. Whether you're building enterprise applications or small utilities, this pattern helps you write flexible and maintainable code.


Thursday, September 25, 2025

Write a program to Generate all possible permutations of the string "ABCDEF" using C#.

 Since "ABCDEF" has 6 characters, the number of permutations = 6! = 720.

Here’s a C# program to generate and print them:

using System; using System.Collections.Generic; class Program { static void Main() { string input = "ABCDEF"; var results = new List<string>(); GetPermutations(input.ToCharArray(), 0, results); Console.WriteLine($"Total Permutations: {results.Count}"); foreach (var str in results) { Console.WriteLine(str); } } static void GetPermutations(char[] arr, int index, List<string> results) { if (index == arr.Length - 1) { results.Add(new string(arr)); } else { for (int i = index; i < arr.Length; i++) { Swap(ref arr[index], ref arr[i]); GetPermutations(arr, index + 1, results); Swap(ref arr[index], ref arr[i]); // backtrack } } } static void Swap(ref char a, ref char b) { if (a == b) return; char temp = a; a = b; b = temp; } }

🔹 How it works:

  1. Uses recursion to generate all permutations.

  2. Swaps characters, calls recursively, then backtracks to restore the original order.

  3. Stores all unique permutations in a List<string>.


🔹 Sample Output:

Total Permutations: 720 ABCDEF ABCDE F ABCDFE ABCEDF ... FEDCBA

👉 This prints all 720 unique permutations of "ABCDEF".

Blog Archive

Don't Copy

Protected by Copyscape Online Plagiarism Checker

Pages