codingstuff.io
ExploreTutorialsProblemsCS Subjects
Get Started
ExploreTutorialsProblemsCS Subjects
Get Started
codingstuff.io

Master the art of building software through interactive tutorials, real-world problems, and guided projects.

Pune, Maharashtra, India

codingstuffmail@gmail.com

Product

  • Explore
  • Tutorials
  • Problems
  • CS Subjects

Company

  • About
  • Contact
  • Privacy Policy
  • Terms & Conditions
  • Sitemap

© 2026 codingstuff.io. All rights reserved.

Built with ❤️ for developers everywhere

/
/
All Subjects
🧩

OOP Concepts

23 chapters

1Procedural vs Object-Oriented2Classes, Objects, & Instantiation3Constructors & Destructors4Static Members & Methods5Encapsulation & Access Modifiers6Data Abstraction7Inheritance Types (Single, Multiple)8Compile-Time Polymorphism (Overloading)9Polymorphism & Interfaces10Run-Time Polymorphism (Overriding)11Virtual Functions & V-Tables12Interfaces & Abstract Classes13Generic Programming (Templates & Generics)14Exception Handling in OOP15SOLID Design Principles16Composition over Inheritance17Coupling & Cohesion18UML Diagrams Basics19Creational Patterns (Singleton, Factory)20Structural Patterns (Adapter, Decorator)21Behavioral Patterns (Observer, Strategy)22MVC Architecture Pattern23Object Serialization & Cloning
SubjectsOOP Concepts

Behavioral Patterns (Observer, Strategy)

Updated 2026-04-29
2 min read

Behavioral Patterns (Observer, Strategy)

Behavioral patterns are concerned with algorithms and the assignment of responsibilities between objects. They describe not just patterns of objects or classes but also the patterns of communication between them.

1. The Observer Pattern

Intent: Define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically.

Real-World Analogy

Think of a YouTube channel. You subscribe to a channel. When the creator uploads a new video, YouTube automatically notifies all subscribers. You don't have to keep refreshing the channel page to check for new content.

The Problem

Imagine a weather station that measures temperature. Multiple display elements (a phone app, a web dashboard, a smart watch) all need to update whenever the temperature changes. Without the Observer pattern, the weather station would need hardcoded references to every display, and adding a new display would require modifying the station's code.

The Solution

import java.util.ArrayList;
import java.util.List;

// The Subject (Publisher)
interface Subject {
    void subscribe(Observer o);
    void unsubscribe(Observer o);
    void notifyObservers();
}

// The Observer (Subscriber)
interface Observer {
    void update(float temperature);
}

class WeatherStation implements Subject {
    private List<Observer> observers = new ArrayList<>();
    private float temperature;

    public void subscribe(Observer o) { observers.add(o); }
    public void unsubscribe(Observer o) { observers.remove(o); }

    public void notifyObservers() {
        for (Observer o : observers) {
            o.update(temperature);
        }
    }

    public void setTemperature(float temp) {
        this.temperature = temp;
        notifyObservers(); // Automatically notify all subscribers!
    }
}

class PhoneApp implements Observer {
    public void update(float temperature) {
        System.out.println("Phone App: Temperature is " + temperature + " C");
    }
}

class WebDashboard implements Observer {
    public void update(float temperature) {
        System.out.println("Dashboard: Temperature is " + temperature + " C");
    }
}

// Usage
WeatherStation station = new WeatherStation();
station.subscribe(new PhoneApp());
station.subscribe(new WebDashboard());
station.setTemperature(25.5f);
// Output:
// Phone App: Temperature is 25.5 C
// Dashboard: Temperature is 25.5 C

Adding a SmartWatch display requires zero changes to WeatherStation.

2. The Strategy Pattern

Intent: Define a family of algorithms, encapsulate each one, and make them interchangeable. Strategy lets the algorithm vary independently from clients that use it.

Real-World Analogy

When booking a ride, the transportation app lets you choose between different pricing strategies: Economy, Premium, or Pool. Each strategy calculates the fare differently, but the booking workflow remains the same.

The Problem

A navigation app needs to support different routing algorithms: driving, walking, and cycling. Without the Strategy pattern, the route calculation method would be a massive if-else block that grows every time a new mode is added.

The Solution

// The Strategy Interface
interface RouteStrategy {
    String calculateRoute(String origin, String destination);
}

// Concrete Strategies
class DrivingStrategy implements RouteStrategy {
    public String calculateRoute(String o, String d) {
        return "Driving route from " + o + " to " + d + " via highways";
    }
}

class WalkingStrategy implements RouteStrategy {
    public String calculateRoute(String o, String d) {
        return "Walking route from " + o + " to " + d + " via parks";
    }
}

class CyclingStrategy implements RouteStrategy {
    public String calculateRoute(String o, String d) {
        return "Cycling route from " + o + " to " + d + " via bike lanes";
    }
}

// The Context
class Navigator {
    private RouteStrategy strategy;

    void setStrategy(RouteStrategy strategy) {
        this.strategy = strategy;
    }

    void navigate(String origin, String destination) {
        String route = strategy.calculateRoute(origin, destination);
        System.out.println(route);
    }
}

// Usage: The algorithm can be changed at RUNTIME
Navigator nav = new Navigator();
nav.setStrategy(new DrivingStrategy());
nav.navigate("Home", "Office");
// Output: Driving route from Home to Office via highways

nav.setStrategy(new CyclingStrategy());
nav.navigate("Home", "Office");
// Output: Cycling route from Home to Office via bike lanes

The Navigator class doesn't know or care how the route is calculated. It delegates the algorithm to the injected strategy object. Swapping algorithms at runtime is as simple as calling setStrategy().



PreviousStructural Patterns (Adapter, Decorator)NextMVC Architecture Pattern

Recommended Gear

Structural Patterns (Adapter, Decorator)MVC Architecture Pattern