Header Ads Widget

Responsive Advertisement

Ticker

6/recent/ticker-posts

Software design patterns in C#

In C#, several software design patterns are commonly used to address various design challenges. Some of the most frequently used patterns include:

1. Singleton Pattern

Purpose: Ensures that a class has only one instance and provides a global point of access to it.

Usage: Useful for managing global state or shared resources, such as configuration settings.

Example:

public class Singleton

{

    private static Singleton _instance;

    private static readonly object _lock = new object();

    private Singleton() { }

    public static Singleton Instance

    {

        get

        {

            lock (_lock)

            {

                if (_instance == null)

                {

                    _instance = new Singleton();

                }

                return _instance;

            }

        }

    }

}


2. Factory Method Pattern

Purpose: Defines an interface for creating objects but allows subclasses to alter the type of objects that will be created.

Usage: Useful when a class cannot anticipate the class of objects it must create.

Example:

public abstract class Product

{

    public abstract string Name { get; }

}

public class ConcreteProductA : Product

{

    public override string Name => "Product A";

}

public class ConcreteProductB : Product

{

    public override string Name => "Product B";

}

public abstract class Creator

{

    public abstract Product FactoryMethod();

}

public class ConcreteCreatorA : Creator

{

    public override Product FactoryMethod()

    {

        return new ConcreteProductA();

    }

}

public class ConcreteCreatorB : Creator

{

    public override Product FactoryMethod()

    {

        return new ConcreteProductB();

    }

}



Post a Comment

0 Comments