{"id":110052,"date":"2026-05-07T15:35:12","date_gmt":"2026-05-07T10:05:12","guid":{"rendered":"https:\/\/www.guvi.in\/blog\/?p=110052"},"modified":"2026-05-07T15:35:13","modified_gmt":"2026-05-07T10:05:13","slug":"what-is-design-patterns","status":"publish","type":"post","link":"https:\/\/www.guvi.in\/blog\/what-is-design-patterns\/","title":{"rendered":"What is Design Patterns Tutorial: Learn with Real Code Examples\u00a0\u00a0\u00a0"},"content":{"rendered":"\n<p>Every developer eventually hits the same wall. The code works, but it is a mess. Adding a new feature breaks three other things. The same logic appears in five different places. A colleague asks how the code works and you cannot explain it in less than ten minutes. Design patterns are the solution to exactly these problems.<\/p>\n\n\n\n<p>This design patterns tutorial is different from most. It does not just explain what patterns are. It walks you through the most important ones step by step, with real code examples in Python and JavaScript that you can follow even as a beginner. By the end of this design patterns tutorial, you will know what patterns are, how to read them, and how to write them, how to read them in code, and how to write them yourself.<\/p>\n\n\n\n<p><strong>Quick Answer<\/strong><\/p>\n\n\n\n<p>A design pattern is a reusable, named solution to a common programming problem. There are 23 classic patterns grouped into three categories: Creational (how objects are made), Structural (how objects are connected), and Behavioral (how objects talk to each other). This design patterns tutorial covers the 8 most important patterns with code examples you can run today.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>What Are Design Patterns?&nbsp;<\/strong><\/h2>\n\n\n\n<p><em>Imagine you work in a kitchen. Every day, new chefs join and face the same problems. How do you keep sauces from burning? How do you time three dishes to finish at the same moment? Experienced chefs pass down named techniques. &#8220;Use the bain-marie for the chocolate sauce.&#8221; Every chef immediately knows what to do. No one reinvents it.<\/em><\/p>\n\n\n\n<p>Design patterns are exactly that, and this design patterns tutorial will prove it with real code. Named, proven solutions that experienced developers pass down. You do not invent them. You learn them, recognise when to use them, and apply them.<\/p>\n\n\n\n<p><strong>What this design patterns tutorial gives you:<\/strong><\/p>\n\n\n\n<ul>\n<li><strong>A shared language:<\/strong> Say &#8220;use the Observer pattern here&#8221; and every developer on your team knows exactly what the code structure will look like<\/li>\n\n\n\n<li><strong>Battle-tested solutions:<\/strong> Each pattern has been refined across thousands of projects over decades<\/li>\n\n\n\n<li><strong>Cleaner code:<\/strong> Patterns reduce duplication, loosen coupling, and make change easier<\/li>\n\n\n\n<li><strong>Interview readiness:<\/strong> Design pattern questions appear in almost every mid and senior developer interview<\/li>\n<\/ul>\n\n\n\n<p><strong>The three categories at a glance:<\/strong><\/p>\n\n\n\n<figure class=\"wp-block-table\"><table><tbody><tr><td><strong>Category<\/strong><\/td><td><strong>Solves<\/strong><\/td><td><strong>Key patterns<\/strong><\/td><\/tr><tr><td>Creational<\/td><td>How objects are created<\/td><td>Singleton, Factory, Builder<\/td><\/tr><tr><td>Structural<\/td><td>How objects are organised and connected<\/td><td>Adapter, Decorator, Facade<\/td><\/tr><tr><td>Behavioral<\/td><td>How objects communicate and share responsibility<\/td><td>Observer, Strategy<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<p><em>Every major framework you use was built using patterns from a design patterns tutorial like this one. React uses Observer. Express uses Decorator. Java&#8217;s Collections use Iterator and Strategy throughout. Once you work through this design patterns tutorial, you will recognise these patterns in code you write every day.<\/em><\/p>\n\n\n\n<p>Do check out HCL GUVI\u2019s <a href=\"https:\/\/www.guvi.in\/zen-class\/ai-software-development-course\/?utm_source=blog&amp;utm_medium=hyperlink&amp;utm_campaign=what-is-design-patterns-tutorial-learn-with-real-code-examples\" target=\"_blank\" rel=\"noreferrer noopener\">AI Software Development Course<\/a> if you want to master <a href=\"https:\/\/www.guvi.in\/blog\/what-is-system-design\/\" target=\"_blank\" rel=\"noreferrer noopener\">system design<\/a> and design patterns with real-world coding skills. This industry-focused program offers 300+ hours of hands-on learning, live sessions, and certifications from IITM Pravartak and MongoDB, helping you build scalable applications, understand architecture, and become job-ready with practical projects.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>Creational Patterns: Controlling How Objects Are Created<\/strong><\/h2>\n\n\n\n<p>The first category in any design patterns tutorial is Creational patterns, which deal with object creation. The goal is to make creation flexible, controlled, and decoupled from the rest of the code.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>1. Singleton Pattern<\/strong><\/h3>\n\n\n\n<p><strong>The problem Singleton solves in this design patterns tutorial:<\/strong> You need exactly one instance of a class in your entire application. No duplicates. Not two database connections, not two configuration managers, not two loggers.<\/p>\n\n\n\n<p><strong>Real-world analogy:<\/strong> A company has one HR manager. Every department goes to the same person. Creating two HR managers causes confusion and conflicting decisions.<\/p>\n\n\n\n<p><strong>How it works step by step:<\/strong><\/p>\n\n\n\n<ul>\n<li><strong>Step 1:<\/strong> The class keeps a private reference to its own single instance<\/li>\n\n\n\n<li><strong>Step 2:<\/strong> The constructor is made private so no one can call <strong>new<\/strong> on it directly<\/li>\n\n\n\n<li><strong>Step 3:<\/strong> A public method called <strong>getInstance()<\/strong> checks if an instance already exists<\/li>\n\n\n\n<li><strong>Step 4:<\/strong> If yes, it returns the existing one. If no, it creates one and stores it.<\/li>\n<\/ul>\n\n\n\n<p><strong>Python code example:<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>class DatabaseConnection:\n    _instance = None  # Step 1: private reference\n\n    def __new__(cls):\n        if cls._instance is None:  # Step 3: check if exists\n            cls._instance = super().__new__(cls)\n            cls._instance.connection = \"Connected to DB\"\n        return cls._instance  # Step 4: return existing\n\n# Usage\ndb1 = DatabaseConnection()\ndb2 = DatabaseConnection()\n\nprint(db1 is db2)  # True - same object\nprint(db1.connection)  # Connected to DB\n<\/code><\/pre>\n\n\n\n<p><strong>When to use Singleton:<\/strong><\/p>\n\n\n\n<ul>\n<li>Database connection pools<\/li>\n\n\n\n<li>Application configuration settings<\/li>\n\n\n\n<li>Logging services<\/li>\n\n\n\n<li>Cache managers<\/li>\n<\/ul>\n\n\n\n<p><strong>When NOT to use it:<\/strong><\/p>\n\n\n\n<ul>\n<li>When multiple instances would be fine (Singleton adds unnecessary constraint in this case)<\/li>\n\n\n\n<li>When testing is critical. Singletons hold global state and make unit testing significantly harder.<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>2. Factory Method Pattern<\/strong><\/h3>\n\n\n\n<p><strong>The problem Factory solves in this design patterns tutorial:<\/strong> You need to create different types of objects but do not want the calling code to know which exact class it is creating. Creation details should be hidden.<\/p>\n\n\n\n<p><strong>Real-world analogy:<\/strong> You walk into a car dealership and ask for &#8220;a red sedan.&#8221; You do not know which factory made it, which assembly line it came off, or which workers built it. You just asked for the car. The dealership handles the creation details.<\/p>\n\n\n\n<p><strong>How it works step by step:<\/strong><\/p>\n\n\n\n<ul>\n<li><strong>Step 1:<\/strong> Define an interface or base class that all products share<\/li>\n\n\n\n<li><strong>Step 2:<\/strong> Create a Factory class with a method that takes a parameter<\/li>\n\n\n\n<li><strong>Step 3:<\/strong> Inside the factory method, use a condition to decide which class to instantiate<\/li>\n\n\n\n<li><strong>Step 4:<\/strong> Return the created object. The caller only sees the base type.<\/li>\n<\/ul>\n\n\n\n<p><strong>Python code example:<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code># Step 1: Base class all notifications share\nclass Notification:\n    def send(self, message):\n        pass\n\nclass EmailNotification(Notification):\n    def send(self, message):\n        print(f\"Sending EMAIL: {message}\")\n\nclass SMSNotification(Notification):\n    def send(self, message):\n        print(f\"Sending SMS: {message}\")\n\nclass PushNotification(Notification):\n    def send(self, message):\n        print(f\"Sending PUSH: {message}\")\n\n# Step 2-3: The Factory\nclass NotificationFactory:\n    @staticmethod\n    def create(notif_type):\n        if notif_type == \"email\":\n            return EmailNotification()\n        elif notif_type == \"sms\":\n            return SMSNotification()\n        elif notif_type == \"push\":\n            return PushNotification()\n        raise ValueError(f\"Unknown type: {notif_type}\")\n\n# Step 4: Usage - caller does not know which class was created\nnotif = NotificationFactory.create(\"email\")\nnotif.send(\"Your order has shipped!\")\n# Output: Sending EMAIL: Your order has shipped!\n<\/code><\/pre>\n\n\n\n<p><strong>When to use Factory:<\/strong><\/p>\n\n\n\n<ul>\n<li>When the exact type of object depends on user input or configuration<\/li>\n\n\n\n<li>When you want to centralise creation logic in one place<\/li>\n\n\n\n<li>When adding a new type should not require changing existing code<\/li>\n<\/ul>\n\n\n\n<p><strong><em>Riddle:<\/em><\/strong><em> Your app currently supports PayPal and Credit Card payments. Your manager asks you to add UPI and Crypto next month. Without a Factory, how many files do you change? With a Factory, how many?<\/em><\/p>\n\n\n\n<p><strong><em>Answer:<\/em><\/strong><em> Without a Factory, you likely change the checkout logic, the payment UI, the validation rules, and the billing records, all scattered across multiple files. With a Factory, you add one new PaymentMethod class and register it in the factory. One file. Everything else stays the same. This is why the Factory pattern exists.<\/em><\/p>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>3. Builder Pattern<\/strong><\/h3>\n\n\n\n<p><strong>The problem Builder solves in this design patterns tutorial:<\/strong> Creating an object requires many optional parameters. A constructor with ten parameters is confusing and error-prone. You forget which position is which.<\/p>\n\n\n\n<p><strong>Real-world analogy:<\/strong> Ordering a custom pizza. You say the size, the base, the sauce, each topping one at a time. The pizza is assembled step by step. You do not shout out every option in one breath.<\/p>\n\n\n\n<p><strong>How it works step by step:<\/strong><\/p>\n\n\n\n<ul>\n<li><strong>Step 1:<\/strong> Create a Builder class that stores parameters as properties<\/li>\n\n\n\n<li><strong>Step 2:<\/strong> Add methods for each parameter that return <strong>self<\/strong> (for chaining)<\/li>\n\n\n\n<li><strong>Step 3:<\/strong> Add a <strong>build()<\/strong> method that creates and returns the final object<\/li>\n\n\n\n<li><strong>Step 4:<\/strong> Chain the method calls to set only the options you need<\/li>\n<\/ul>\n\n\n\n<p><strong>Python code example:<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>class Pizza:\n    def __init__(self, size, crust, sauce, toppings):\n        self.size = size\n        self.crust = crust\n        self.sauce = sauce\n        self.toppings = toppings\n\n    def __str__(self):\n        return f\"{self.size} pizza, {self.crust} crust, {self.sauce} sauce, toppings: {self.toppings}\"\n\n# Step 1-3: The Builder\nclass PizzaBuilder:\n    def __init__(self):\n        self.size = \"medium\"\n        self.crust = \"thin\"\n        self.sauce = \"tomato\"\n        self.toppings = &#91;]\n\n    def set_size(self, size):\n        self.size = size\n        return self  # Step 2: returns self for chaining\n\n    def set_crust(self, crust):\n        self.crust = crust\n        return self\n\n    def add_topping(self, topping):\n        self.toppings.append(topping)\n        return self\n\n    def build(self):  # Step 3: creates the final object\n        return Pizza(self.size, self.crust, self.sauce, self.toppings)\n\n# Step 4: Usage\npizza = (PizzaBuilder()\n         .set_size(\"large\")\n         .set_crust(\"stuffed\")\n         .add_topping(\"mushrooms\")\n         .add_topping(\"olives\")\n         .build())\n\nprint(pizza)\n# Output: large pizza, stuffed crust, tomato sauce, toppings: &#91;'mushrooms', 'olives']\n<\/code><\/pre>\n\n\n\n<p><strong>When to use Builder:<\/strong><\/p>\n\n\n\n<ul>\n<li>Objects with many optional parameters<\/li>\n\n\n\n<li>Step-by-step construction of complex objects<\/li>\n\n\n\n<li>When you want readable, self-documenting object creation code<\/li>\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>Structural Patterns: Organising How Objects Connect<\/strong><\/h2>\n\n\n\n<p>The second section of this design patterns tutorial covers Structural patterns, which deal with how classes are composed into larger structures. They make complex systems easier to navigate.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>4. Adapter Pattern<\/strong><\/h3>\n\n\n\n<p><strong>The problem Adapter solves in this design patterns tutorial:<\/strong> Two pieces of code need to work together but have incompatible interfaces. One expects data in format A, the other provides format B.<\/p>\n\n\n\n<p><strong>Real-world analogy:<\/strong> A universal travel plug adapter. Your UK plug does not fit a US socket. The adapter sits between the two, translating one interface to another. Neither the plug nor the socket changes.<\/p>\n\n\n\n<p><strong>How it works step by step:<\/strong><\/p>\n\n\n\n<ul>\n<li><strong>Step 1:<\/strong> Identify the Target interface your code expects<\/li>\n\n\n\n<li><strong>Step 2:<\/strong> Identify the Adaptee (the incompatible class you cannot change)<\/li>\n\n\n\n<li><strong>Step 3:<\/strong> Create an Adapter class that implements the Target interface<\/li>\n\n\n\n<li><strong>Step 4:<\/strong> Inside the Adapter, call the Adaptee&#8217;s methods and translate the output<\/li>\n<\/ul>\n\n\n\n<p><strong>Python code example:<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code># Your app expects this interface (Target)\nclass JSONLogger:\n    def log(self, data: dict):\n        print(f\"JSON LOG: {data}\")\n\n# A third-party library you cannot change (Adaptee)\nclass OldTextLogger:\n    def write_log(self, text: str):\n        print(f\"TEXT LOG: {text}\")\n\n# Step 3-4: The Adapter bridges the gap\nclass LoggerAdapter:\n    def __init__(self, old_logger: OldTextLogger):\n        self.old_logger = old_logger\n\n    def log(self, data: dict):  # Matches the Target interface\n        # Step 4: translate dict to string for the old logger\n        text = \", \".join(f\"{k}={v}\" for k, v in data.items())\n        self.old_logger.write_log(text)\n\n# Usage - your app calls .log() and never knows about OldTextLogger\nold = OldTextLogger()\nlogger = LoggerAdapter(old)\nlogger.log({\"user\": \"Priya\", \"action\": \"login\"})\n# Output: TEXT LOG: user=Priya, action=login\n<\/code><\/pre>\n\n\n\n<p><strong>When to use Adapter:<\/strong><\/p>\n\n\n\n<ul>\n<li>Integrating third-party libraries with incompatible interfaces<\/li>\n\n\n\n<li>Making legacy code work with new systems without rewriting it<\/li>\n\n\n\n<li>Any time you need to bridge two interfaces you cannot modify<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>5. Decorator Pattern<\/strong><\/h3>\n\n\n\n<p><strong>The problem Decorator solves in this design patterns tutorial:<\/strong> You need to add new behaviour to an object at runtime without modifying its class or creating a separate subclass for every combination.<\/p>\n\n\n\n<p><strong>Real-world analogy:<\/strong> Ordering coffee. You start with a plain espresso. Add milk. Now it is a latte. Add caramel. Now it is a caramel latte. Each addition wraps the previous one without changing it.<\/p>\n\n\n\n<p><strong>How it works step by step:<\/strong><\/p>\n\n\n\n<ul>\n<li><strong>Step 1:<\/strong> Define a base component interface or class<\/li>\n\n\n\n<li><strong>Step 2:<\/strong> Create concrete components that implement the base<\/li>\n\n\n\n<li><strong>Step 3:<\/strong> Create a Decorator class that also implements the base but wraps another component<\/li>\n\n\n\n<li><strong>Step 4:<\/strong> Override the relevant method to add behaviour before or after calling the wrapped component<\/li>\n<\/ul>\n\n\n\n<p><strong>Python code example:<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code># Step 1: Base interface\nclass Coffee:\n    def cost(self):\n        return 0\n    def description(self):\n        return \"\"\n\n# Step 2: Concrete component\nclass Espresso(Coffee):\n    def cost(self):\n        return 50  # Rs. 50\n    def description(self):\n        return \"Espresso\"\n\n# Step 3-4: Decorators\nclass MilkDecorator(Coffee):\n    def __init__(self, coffee: Coffee):\n        self._coffee = coffee  # wraps an existing coffee\n\n    def cost(self):\n        return self._coffee.cost() + 20  # adds to existing cost\n\n    def description(self):\n        return self._coffee.description() + \" + Milk\"\n\nclass CaramelDecorator(Coffee):\n    def __init__(self, coffee: Coffee):\n        self._coffee = coffee\n\n    def cost(self):\n        return self._coffee.cost() + 30\n\n    def description(self):\n        return self._coffee.description() + \" + Caramel\"\n\n# Usage\norder = Espresso()\norder = MilkDecorator(order)      # wrap with milk\norder = CaramelDecorator(order)   # wrap with caramel\n\nprint(order.description())  # Espresso + Milk + Caramel\nprint(f\"Rs. {order.cost()}\")  # Rs. 100\n<\/code><\/pre>\n\n\n\n<p><strong>When to use Decorator:<\/strong><\/p>\n\n\n\n<ul>\n<li>Adding optional features to objects without creating a subclass for every combination<\/li>\n\n\n\n<li>Middleware in web frameworks (auth, logging, rate limiting)<\/li>\n\n\n\n<li>File stream processing (compression, encryption, buffering)<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>6. Facade Pattern<\/strong><\/h3>\n\n\n\n<p><strong>The problem Facade solves in this design patterns tutorial:<\/strong> A complex subsystem has many classes and methods. The calling code should not need to know all of them just to do one simple thing.<\/p>\n\n\n\n<p><strong>Real-world analogy:<\/strong> A hotel concierge. You say &#8220;I need a restaurant booking, a taxi, and a wake-up call at 7am.&#8221; You do not call the restaurant, the taxi company, and the front desk separately. The concierge handles all of it. One interface. All the complexity hidden behind it.<\/p>\n\n\n\n<p><strong>How it works step by step:<\/strong><\/p>\n\n\n\n<ul>\n<li><strong>Step 1:<\/strong> Identify the complex subsystem with many components<\/li>\n\n\n\n<li><strong>Step 2:<\/strong> Create a Facade class that the caller will interact with<\/li>\n\n\n\n<li><strong>Step 3:<\/strong> Inside the Facade, hold references to the subsystem components<\/li>\n\n\n\n<li><strong>Step 4:<\/strong> Create simple methods that coordinate the complex steps internally<\/li>\n<\/ul>\n\n\n\n<p><strong>Python code example:<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code># Step 1: Complex subsystem with many moving parts\nclass VideoDecoder:\n    def decode(self, file):\n        print(f\"Decoding {file}\")\n\nclass AudioExtractor:\n    def extract(self, file):\n        print(f\"Extracting audio from {file}\")\n\nclass SubtitleParser:\n    def parse(self, file):\n        print(f\"Parsing subtitles for {file}\")\n\nclass VideoUploader:\n    def upload(self, file):\n        print(f\"Uploading {file} to CDN\")\n\n# Step 2-4: The Facade\nclass VideoProcessingFacade:\n    def __init__(self):\n        self.decoder = VideoDecoder()\n        self.audio = AudioExtractor()\n        self.subtitles = SubtitleParser()\n        self.uploader = VideoUploader()\n\n    def process_and_publish(self, filename):\n        print(f\"--- Processing {filename} ---\")\n        self.decoder.decode(filename)\n        self.audio.extract(filename)\n        self.subtitles.parse(filename)\n        self.uploader.upload(filename)\n        print(\"Done!\")\n\n# Usage - caller does one thing, Facade handles everything\nfacade = VideoProcessingFacade()\nfacade.process_and_publish(\"lecture_video.mp4\")\n<\/code><\/pre>\n\n\n\n<p><strong>When to use Facade:<\/strong><\/p>\n\n\n\n<ul>\n<li>Simplifying complex library or framework interactions<\/li>\n\n\n\n<li>Creating a clean API for a layered system<\/li>\n\n\n\n<li>Hiding legacy complexity behind a modern interface<\/li>\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>Behavioral Patterns: How Objects Communicate<\/strong><\/h2>\n\n\n\n<p>The final section of this design patterns tutorial covers Behavioral patterns, which deal with communication between objects and the assignment of responsibilities.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>7. Observer Pattern<\/strong><\/h3>\n\n\n\n<p><strong>The problem Observer solves in this design patterns tutorial:<\/strong> When one object changes, several other objects need to be notified and updated automatically. You do not want the Subject to know the details of each Observer.<\/p>\n\n\n\n<p><strong>Real-world analogy:<\/strong> A YouTube channel. When a creator uploads a video, all subscribers get notified automatically. The creator does not call each subscriber one by one. Subscribers register themselves. Unsubscribers stop receiving notifications.<\/p>\n\n\n\n<p><strong>How it works step by step:<\/strong><\/p>\n\n\n\n<ul>\n<li><strong>Step 1:<\/strong> Create a Subject class that holds a list of observers and a method to notify them<\/li>\n\n\n\n<li><strong>Step 2:<\/strong> Add <strong>subscribe()<\/strong> and <strong>unsubscribe()<\/strong> methods to manage the observer list<\/li>\n\n\n\n<li><strong>Step 3:<\/strong> When state changes, call <strong>notify()<\/strong> which loops through all observers<\/li>\n\n\n\n<li><strong>Step 4:<\/strong> Each Observer implements an <strong>update()<\/strong> method that is called by the Subject<\/li>\n<\/ul>\n\n\n\n<p><strong>Python code example:<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code># Step 1-3: The Subject\nclass StockMarket:\n    def __init__(self):\n        self._observers = &#91;]\n        self._price = 0\n\n    def subscribe(self, observer):   # Step 2\n        self._observers.append(observer)\n\n    def unsubscribe(self, observer):\n        self._observers.remove(observer)\n\n    def notify(self):                # Step 3\n        for observer in self._observers:\n            observer.update(self._price)\n\n    def set_price(self, price):\n        self._price = price\n        print(f\"\\nPrice changed to Rs. {price}\")\n        self.notify()\n\n# Step 4: Observers implement update()\nclass MobileApp:\n    def update(self, price):\n        print(f\"  Mobile App alert: Price is now Rs. {price}\")\n\nclass EmailAlert:\n    def update(self, price):\n        print(f\"  Email sent: Current price Rs. {price}\")\n\nclass TradingBot:\n    def update(self, price):\n        if price &lt; 1000:\n            print(f\"  Trading Bot: BUY at Rs. {price}\")\n        else:\n            print(f\"  Trading Bot: HOLD at Rs. {price}\")\n\n# Usage\nmarket = StockMarket()\nmarket.subscribe(MobileApp())\nmarket.subscribe(EmailAlert())\nmarket.subscribe(TradingBot())\n\nmarket.set_price(950)\nmarket.set_price(1200)\n<\/code><\/pre>\n\n\n\n<p><strong>Output:<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>Price changed to Rs. 950\n  Mobile App alert: Price is now Rs. 950\n  Email sent: Current price Rs. 950\n  Trading Bot: BUY at Rs. 950\n\nPrice changed to Rs. 1200\n  Mobile App alert: Price is now Rs. 1200\n  Email sent: Current price Rs. 1200\n  Trading Bot: HOLD at Rs. 1200\n<\/code><\/pre>\n\n\n\n<p><strong>When to use Observer:<\/strong><\/p>\n\n\n\n<ul>\n<li>Event-driven systems (button clicks, keyboard events)<\/li>\n\n\n\n<li>Real-time notification systems (price alerts, live scores)<\/li>\n\n\n\n<li>React&#8217;s state and effect system uses Observer internally<\/li>\n\n\n\n<li>Any time multiple parts of an app must react to one change<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>8. Strategy Pattern<\/strong><\/h3>\n\n\n\n<p><strong>The problem Strategy solves in this design patterns tutorial:<\/strong> You have multiple ways to perform the same task. Switching between them requires messy if-else chains that grow every time a new option is added.<\/p>\n\n\n\n<p><strong>Real-world analogy:<\/strong> Google Maps route options. Same destination, different strategies. Fastest. Shortest. Avoid tolls. Avoid highways. You pick a strategy. The navigation engine switches without any other code changing.<\/p>\n\n\n\n<p><strong>How it works step by step:<\/strong><\/p>\n\n\n\n<ul>\n<li><strong>Step 1:<\/strong> Define a Strategy interface with one method all strategies share<\/li>\n\n\n\n<li><strong>Step 2:<\/strong> Create a concrete class for each algorithm that implements the interface<\/li>\n\n\n\n<li><strong>Step 3:<\/strong> Create a Context class that holds a reference to the current strategy<\/li>\n\n\n\n<li><strong>Step 4:<\/strong> Add a <strong>set_strategy()<\/strong> method to swap strategies at runtime<\/li>\n<\/ul>\n\n\n\n<p><strong>Python code example:<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code># Step 1: Strategy interface\nclass SortStrategy:\n    def sort(self, data):\n        pass\n\n# Step 2: Concrete strategies\nclass BubbleSort(SortStrategy):\n    def sort(self, data):\n        print(\"Using Bubble Sort\")\n        return sorted(data)  # simplified for demo\n\nclass QuickSort(SortStrategy):\n    def sort(self, data):\n        print(\"Using Quick Sort\")\n        return sorted(data)  # simplified for demo\n\nclass MergeSort(SortStrategy):\n    def sort(self, data):\n        print(\"Using Merge Sort\")\n        return sorted(data)  # simplified for demo\n\n# Step 3-4: The Context\nclass DataProcessor:\n    def __init__(self, strategy: SortStrategy):\n        self._strategy = strategy\n\n    def set_strategy(self, strategy: SortStrategy):  # Step 4\n        self._strategy = strategy\n\n    def process(self, data):\n        return self._strategy.sort(data)\n\n# Usage - swap strategies at runtime, no if-else needed\nnumbers = &#91;64, 25, 12, 22, 11]\n\nprocessor = DataProcessor(BubbleSort())\nprint(processor.process(numbers))\n\nprocessor.set_strategy(QuickSort())   # switch strategy\nprint(processor.process(numbers))\n<\/code><\/pre>\n\n\n\n<p><strong>When to use Strategy:<\/strong><\/p>\n\n\n\n<ul>\n<li>Payment methods (CreditCard, PayPal, UPI, Crypto)<\/li>\n\n\n\n<li>Sorting algorithms (let the caller choose)<\/li>\n\n\n\n<li>Validation rules that differ by user type<\/li>\n\n\n\n<li>Compression algorithms (ZIP, GZIP, BZIP)<\/li>\n\n\n\n<li>Any time an if-else chain grows every time a new option is added<\/li>\n<\/ul>\n\n\n\n<p><strong><em>Riddle:<\/em><\/strong><em> Your e-commerce app has a discount calculator. Right now it uses if-else to check student discount, festive discount, loyalty discount, and employee discount. Your manager says two new discount types are coming next month. Every time a discount is added, three developers edit the same file and conflicts happen. Which pattern solves this cleanly?<\/em><\/p>\n\n\n\n<p><strong><em>Answer:<\/em><\/strong><em> Strategy pattern. Each discount type becomes its own DiscountStrategy class. The calculator holds a reference to whichever strategy is active. Adding a new discount means adding one new class and registering it. Zero changes to the calculator itself. No more conflicts. No more growing if-else chains.<\/em><\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>Putting It All Together: Which Pattern to Use When<\/strong><\/h2>\n\n\n\n<p>After working through this design patterns tutorial, use this table as your quick reference.<\/p>\n\n\n\n<figure class=\"wp-block-table\"><table><tbody><tr><td><strong>Situation<\/strong><\/td><td><strong>Pattern to Use<\/strong><\/td><\/tr><tr><td>Need exactly one instance of a class<\/td><td>Singleton<\/td><\/tr><tr><td>Create objects without knowing their exact class<\/td><td>Factory Method<\/td><\/tr><tr><td>Build complex objects with many optional steps<\/td><td>Builder<\/td><\/tr><tr><td>Connect two incompatible interfaces<\/td><td>Adapter<\/td><\/tr><tr><td>Add behaviour to objects without changing their class<\/td><td>Decorator<\/td><\/tr><tr><td>Simplify access to a complex subsystem<\/td><td>Facade<\/td><\/tr><tr><td>Notify multiple objects when one object changes<\/td><td>Observer<\/td><\/tr><tr><td>Switch algorithms or behaviours at runtime<\/td><td>Strategy<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>Common Beginner Mistakes in This Design Patterns Tutorial<\/strong><\/h2>\n\n\n\n<ul>\n<li><strong>Overusing Singleton from this design patterns tutorial:<\/strong> Not every class needs to be a Singleton. Use it only when truly one instance is needed. Overuse makes testing very hard.<\/li>\n\n\n\n<li><strong>Applying design patterns tutorial patterns before the problem exists:<\/strong> Do not start a project by deciding which patterns to use. Write clean code first. Patterns emerge when pain appears.<\/li>\n\n\n\n<li><strong>Copying design patterns tutorial code without understanding it:<\/strong> Every code example in this design patterns tutorial has a reason. If you copy it without knowing why each part exists, you will not know how to adapt it.<\/li>\n\n\n\n<li><strong>Confusing the Decorator from this design patterns tutorial with Inheritance:<\/strong> Decorator adds behaviour at runtime by wrapping objects. Inheritance adds behaviour at compile time by extending classes. They solve different problems.<\/li>\n\n\n\n<li><strong>Forgetting to deregister Observers from this design patterns tutorial:<\/strong> If an object subscribes to events and is never unsubscribed, it stays in memory forever. Always call <strong>unsubscribe()<\/strong> when an Observer is no longer needed.<\/li>\n<\/ul>\n\n\n\n<div style=\"background-color: #099f4e; border: 3px solid #110053; border-radius: 12px; padding: 18px 22px; color: #FFFFFF; font-size: 18px; font-family: Montserrat, Helvetica, sans-serif; line-height: 1.6; box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15); max-width: 750px; margin: 22px auto;\">\n  <h3 style=\"margin-top: 0; font-size: 22px; font-weight: 700; color: #ffffff;\">\ud83d\udca1 Did You Know?<\/h3>\n  <ul style=\"padding-left: 20px; margin: 10px 0;\">\n    <li>The Gang of Four book, the original design patterns tutorial, was published in 1994 and has never gone out of print. It remains the foundational reference for every design patterns tutorial written since.<\/li>\n    <li>Design patterns are language-agnostic. Every example in this design patterns tutorial was written in Python, but the exact same structure works in JavaScript, Java, C#, TypeScript, and any other object-oriented language. Only the syntax changes.<\/li>\n  <\/ul>\n<\/div>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>Conclusion<\/strong><\/h2>\n\n\n\n<p>This design patterns tutorial has walked through 8 of the 23 classic patterns with working code you can run today. Singleton for one-of-a-kind objects. Factory for flexible creation. Builder for complex construction. Adapter for incompatible interfaces. Decorator for wrapping behaviour. Facade for hiding complexity. Observer for event-driven updates. Strategy for swappable algorithms.<\/p>\n\n\n\n<p>These 8 patterns cover the majority of real-world design problems you will encounter as a developer. The best next step from this design patterns tutorial is to pick one pattern and apply it to code you are already writing.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>FAQs<\/strong><\/h2>\n\n\n<div id=\"rank-math-faq\" class=\"rank-math-block\">\n<div class=\"rank-math-list \">\n<div id=\"faq-question-1778146308580\" class=\"rank-math-list-item\">\n<h3 class=\"rank-math-question \"><strong>1. Which programming language is best for learning design patterns?<\/strong>\u00a0<\/h3>\n<div class=\"rank-math-answer \">\n\n<p>Any object-oriented language works for this design patterns tutorial. Python is ideal for beginners because its syntax is clean and readable. Java and C# are the most common languages in enterprise where patterns appear frequently. Every example in this design patterns tutorial works in any of these languages with minor syntax changes.<\/p>\n\n<\/div>\n<\/div>\n<div id=\"faq-question-1778146330937\" class=\"rank-math-list-item\">\n<h3 class=\"rank-math-question \"><strong>2. Do I need to know all 23 design patterns for interviews?<\/strong><\/h3>\n<div class=\"rank-math-answer \">\n\n<p>No. Knowing the 8 patterns in this design patterns tutorial deeply is far more valuable than knowing all 23 superficially. Interviewers want you to explain a pattern clearly, identify when to use it, and discuss its trade-offs.<\/p>\n\n<\/div>\n<\/div>\n<div id=\"faq-question-1778146352856\" class=\"rank-math-list-item\">\n<h3 class=\"rank-math-question \"><strong>3. Is the Observer pattern the same as event listeners in JavaScript?<\/strong><\/h3>\n<div class=\"rank-math-answer \">\n\n<p>Yes. This design patterns tutorial&#8217;s Observer section maps directly to how JavaScript&#8217;s <strong>addEventListener<\/strong> works. The DOM element is the Subject. Each listener is an Observer. <strong>removeEventListener<\/strong> is the unsubscribe method. This design patterns tutorial&#8217;s Observer example maps directly to how the browser handles events.<\/p>\n\n<\/div>\n<\/div>\n<div id=\"faq-question-1778146376582\" class=\"rank-math-list-item\">\n<h3 class=\"rank-math-question \"><strong>4. Can I use multiple patterns in the same codebase?<\/strong><\/h3>\n<div class=\"rank-math-answer \">\n\n<p>Yes, and most real codebases do. A Factory might create objects that use the Decorator pattern. An Observer might trigger a method in a class that uses Strategy. Patterns complement each other naturally.<\/p>\n\n<\/div>\n<\/div>\n<div id=\"faq-question-1778146400359\" class=\"rank-math-list-item\">\n<h3 class=\"rank-math-question \"><strong>5. How long does it take to get comfortable with design patterns?<\/strong><\/h3>\n<div class=\"rank-math-answer \">\n\n<p>Most developers feel comfortable with the 8 core patterns in this design patterns tutorial after two to four weeks of deliberate practice, meaning reading, coding, and applying them to real projects. Encountering them in real codebases after that accelerates understanding rapidly.<\/p>\n\n<\/div>\n<\/div>\n<\/div>\n<\/div>","protected":false},"excerpt":{"rendered":"<p>Every developer eventually hits the same wall. The code works, but it is a mess. Adding a new feature breaks three other things. The same logic appears in five different places. A colleague asks how the code works and you cannot explain it in less than ten minutes. Design patterns are the solution to exactly [&hellip;]<\/p>\n","protected":false},"author":65,"featured_media":110064,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[959],"tags":[],"views":"33","authorinfo":{"name":"Jebasta","url":"https:\/\/www.guvi.in\/blog\/author\/jebasta\/"},"thumbnailURL":"https:\/\/www.guvi.in\/blog\/wp-content\/uploads\/2026\/05\/design-patterns-tutorial-300x115.webp","jetpack_featured_media_url":"https:\/\/www.guvi.in\/blog\/wp-content\/uploads\/2026\/05\/design-patterns-tutorial-scaled.webp","_links":{"self":[{"href":"https:\/\/www.guvi.in\/blog\/wp-json\/wp\/v2\/posts\/110052"}],"collection":[{"href":"https:\/\/www.guvi.in\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.guvi.in\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.guvi.in\/blog\/wp-json\/wp\/v2\/users\/65"}],"replies":[{"embeddable":true,"href":"https:\/\/www.guvi.in\/blog\/wp-json\/wp\/v2\/comments?post=110052"}],"version-history":[{"count":2,"href":"https:\/\/www.guvi.in\/blog\/wp-json\/wp\/v2\/posts\/110052\/revisions"}],"predecessor-version":[{"id":110066,"href":"https:\/\/www.guvi.in\/blog\/wp-json\/wp\/v2\/posts\/110052\/revisions\/110066"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.guvi.in\/blog\/wp-json\/wp\/v2\/media\/110064"}],"wp:attachment":[{"href":"https:\/\/www.guvi.in\/blog\/wp-json\/wp\/v2\/media?parent=110052"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.guvi.in\/blog\/wp-json\/wp\/v2\/categories?post=110052"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.guvi.in\/blog\/wp-json\/wp\/v2\/tags?post=110052"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}