Monday, 22 September 2025

Design Pattern

🟢 What is a Design Pattern?

A design pattern is a common way to write code to fix a common problem.
Think of it as a ready-made plan.


1️⃣ CREATIONAL PATTERNS

(How to create objects)

✅ Singleton

Goal: Only one object of a class exists.

Example: only one settings object for the whole app.

public class AppSettings { private static AppSettings _instance; private AppSettings() { } public static AppSettings Instance { get { if (_instance == null) _instance = new AppSettings(); return _instance; } } }

Use: var s = AppSettings.Instance;


✅ Factory

Goal: Decide which object to create inside a method.

abstract class Animal { public abstract void Speak(); } class Dog : Animal { public override void Speak() => Console.WriteLine("Woof"); } class Cat : Animal { public override void Speak() => Console.WriteLine("Meow"); } class AnimalFactory { public static Animal Create(string type) { if (type == "dog") return new Dog(); else return new Cat(); } }

Use: Animal a = AnimalFactory.Create("dog"); a.Speak();


✅ Builder

Goal: Build a complex object step by step.

class Pizza { public string Topping; public string Size; } class PizzaBuilder { private Pizza p = new Pizza(); public PizzaBuilder AddTopping(string t){ p.Topping = t; return this; } public PizzaBuilder SetSize(string s){ p.Size = s; return this; } public Pizza Build() => p; }

Use:

var pizza = new PizzaBuilder().AddTopping("Cheese").SetSize("Large").Build();

2️⃣ STRUCTURAL PATTERNS

(How to join or wrap objects)

✅ Adapter

Goal: Make two classes work together even if they don’t match.

interface INew { void DoNew(); } class Old { public void DoOld() => Console.WriteLine("Old work"); } class Adapter : INew { private Old oldObj = new Old(); public void DoNew() => oldObj.DoOld(); }

✅ Facade

Goal: Give a simple interface to complex code.

class Engine { public void Start() => Console.WriteLine("Engine on"); } class Lights { public void On() => Console.WriteLine("Lights on"); } class CarFacade { Engine e = new Engine(); Lights l = new Lights(); public void Drive() { e.Start(); l.On(); Console.WriteLine("Ready!"); } }

Use: new CarFacade().Drive();


✅ Decorator

Goal: Add extra features to an object without changing its class.

interface IMessage { void Send(); } class Email : IMessage { public void Send() => Console.WriteLine("Email"); } class SmsDecorator : IMessage { private IMessage inner; public SmsDecorator(IMessage m) { inner = m; } public void Send() { inner.Send(); Console.WriteLine("SMS too"); } }

3️⃣ BEHAVIORAL PATTERNS

(How objects talk to each other)

✅ Observer

Goal: When one object changes, others know.

class News { public event Action OnChange; public void Publish() => OnChange?.Invoke(); } class Reader { public void Read() => Console.WriteLine("Reader got news"); }

Use:

var news = new News(); var r = new Reader(); news.OnChange += r.Read; news.Publish();

✅ Strategy

Goal: Switch algorithm easily.

interface ISort { void Sort(); } class QuickSort : ISort { public void Sort() => Console.WriteLine("QuickSort"); } class BubbleSort : ISort { public void Sort() => Console.WriteLine("BubbleSort"); } class Sorter { private ISort _strategy; public Sorter(ISort s) { _strategy = s; } public void DoSort() => _strategy.Sort(); }

Use:

new Sorter(new QuickSort()).DoSort();

✅ Command

Goal: Save an action as an object so you can run it later.

interface ICommand { void Execute(); } class HelloCommand : ICommand { public void Execute() => Console.WriteLine("Hello"); } class Invoker { public void Run(ICommand c) => c.Execute(); }

Quick Table

TypePatternSimple Purpose
CreationalSingletonOnly one object
FactoryCreate objects smartly
BuilderBuild big object step by step
StructuralAdapterConnect mismatched classes
FacadeSimple front for complex system
DecoratorAdd features without editing code
BehavioralObserverNotify many when one changes
StrategySwap algorithms easily
CommandStore and run commands later

💡 Tip:

  • Use patterns only when you need them.

  • They make code clean, flexible, and easy to change later.

No comments:

Post a Comment