Aspect Inheritance Composition (Decorator)
Relationship is-a has-a
Flexibility Rigid (single parent) Flexible (many wrappers)
Chaining No Yes
Subclassing Needed for each combo Not needed
Example class A extends B {} class A { constructor(b) {} }
  1. Strategy Design Patterns

    A behavioral design pattern is a software design approach that defines how objects interact and communicate with each other.

    Problem: When multiple components share the same functionality, code duplication occurs.

    image.png

Below is ex if you see here we are passing strategy in the runtime and then calling that and using that just like below

class Product {
    constructor(name, price, strategy) {
        this.price = price;
        this.name = name;
        this.strategy = strategy;
    }

    calculateTotal() {
        return this.strategy.calculateTotal(this.price);
    }
}

class DiscountPricing {
    calculateTotal(price) {
        return price * 0.5;
    }
}

class RegularPricing {
    calculateTotal(price) {
        return price;
    }
}

const prod = new Product("apple", 50, new DiscountPricing());
console.log(prod.calculateTotal())
  1. Observer Design Pattern (Behavioural Design Pattern)

    just as the title as theres observable and observer

    Pros:

    image.png

    ex: amazon stocks for

Q. Implement a product stock alert system where customers get notified when the stock is updated.

class Product {

    constructor(name, stocks) {
        this.name = name;
        this.stocks = stocks;
        this.customerObservers = []
    }

    addObservers(customer) {
        this.customerObservers.push(customer)
    }

    getStock() {
        return this.stocks;
    }

    setStocks(stocks) {
        this.stocks = this.stocks - stocks;
        this.customerObservers.forEach((customer) => customer.notifyCustomer(this))
    }
}

class Notification {
    notify() {
        throw new Error("Implement notify")
    }
}

class EmailNotification extends Notification {
    notify(product, name) {
        console.info(`Email notified ${name} ${product.name}`);
    }
}

class Customer {
    constructor(name, notificationStrategy) {
        this.name = name;
        this.notificationStrategy = notificationStrategy;
    }

    notifyCustomer(product) {
        this.notificationStrategy.notify(product, this.name);
    }
}

const prod = new Product("apple", 10, []);
const customer1 = new Customer("pawan", new EmailNotification());
const customer2 = new Customer("sharma", new EmailNotification());
prod.addObservers(customer1)
prod.addObservers(customer2)
prod.setStocks(10)
  1. Decorator Pattern (Structural Design Pattern – A structural pattern defines how objects and classes are combined to form larger, more complex systems.)

Problem:

Example:

image.png