Design Patterns — Creational, Structural, Behavioral

লেসন ৭ / ৫০

Design Pattern কী?

GoF ২৩টি pattern — common design সমস্যার পরীক্ষিত সমাধান।

Creational

Singleton ⭐

public sealed class Logger {
    private static readonly Lazy<Logger> _i = new(() => new Logger());
    public static Logger Instance => _i.Value;
    private Logger() {}
}

Use: Logger, Config, Cache। Test-এ DI prefer।

Factory

class NotifierFactory {
    static Notifier Create(string type) => type switch {
        "email" => new EmailNotifier(),
        "sms" => new SmsNotifier(),
        _ => throw new()
    };
}

Builder

var pizza = new PizzaBuilder("Large")
    .WithCheese().WithMushroom().Build();

Structural

Adapter

class StripeAdapter : IPayment {
    StripeClient _stripe;
    void Pay(decimal amt) => _stripe.Charge(amt * 100);
}

Decorator ⭐

class MilkDecorator : ICoffee {
    ICoffee _c;
    decimal Cost() => _c.Cost() + 10;
}
ICoffee c = new SugarDecorator(new MilkDecorator(new SimpleCoffee()));

Facade

Complex subsystem-এর simple API (HomeTheaterFacade.WatchMovie)।

Proxy

Lazy load, security, caching।

Behavioral

Observer ⭐

class NewsAgency {
    List<IObserver> _subs = new();
    void Subscribe(IObserver o) => _subs.Add(o);
    void Publish(string news) => _subs.ForEach(o => o.Update(news));
}

Strategy ⭐

interface ISortStrategy { void Sort(int[] a); }
class QuickSort : ISortStrategy {}
class Sorter {
    Sorter(ISortStrategy s) {}
}

Command

Undo/redo, queue — ICommand { Execute(); Undo(); }

Template Method

abstract class Exporter {
    public void Export() {
        Connect(); var d = Fetch();
        Save(Format(d)); Disconnect();
    }
}

State

Object behavior change করে state অনুযায়ী।

Anti-Patterns

  • God Object — সব কাজ এক class-এ
  • Spaghetti Code
  • Magic Numbers
  • Copy-Paste Programming