Design Patterns: Overview, Use Cases, and
Examples
1. Decorator Pattern
Category: Structural Pattern Intent: Attach additional responsibilities to an object dynamically without
modifying its code. It is used when you want to add behavior to individual objects at runtime, in a
flexible and reusable way.
■ Use Case Example:
Suppose you have a Coffee object. You can decorate it with Milk, Sugar, or Whip at runtime without
modifying the base Coffee class.
Code Example (Simplified):
interface Coffee { String getDescription(); double getCost(); }
class SimpleCoffee implements Coffee { ... }
class MilkDecorator implements Coffee { private Coffee coffee; ... }
2. Strategy Pattern
Category: Behavioral 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.
■ Use Case Example:
Payment systems where the customer can choose between Credit Card, PayPal, or UPI at runtime.
Code Example (Simplified):
interface PaymentStrategy { void pay(int amount); }
class CreditCardPayment implements PaymentStrategy { ... }
class PayPalPayment implements PaymentStrategy { ... }
class ShoppingCart { private PaymentStrategy strategy; ... }
3. Factory Method Pattern
Category: Creational Pattern Intent: Define an interface for creating objects, but let subclasses decide
which class to instantiate. It is used when the exact type of the object is determined at runtime.
■ Use Case Example:
Database connector: The client requests a DBConnector, and the Factory decides whether to return
MySQLConnector, OracleConnector, or PostgreSQLConnector.
4. Abstract Factory Pattern
Category: Creational Pattern Intent: Provide an interface for creating families of related objects without
specifying their concrete classes.
■ Use Case Example:
UI toolkit: Create buttons and checkboxes for Windows, Mac, or Linux without changing client code.
5. Composite Pattern
Category: Structural Pattern Intent: Compose objects into tree structures to represent part-whole
hierarchies. It lets clients treat individual objects and compositions of objects uniformly.
■ Use Case Example:
File System (Files and Folders): A folder can contain files or subfolders, but both are treated the same.
Decorator vs Strategy (Quick Summary)
• Decorator → Structural pattern, used to add new behavior dynamically.
• Strategy → Behavioral pattern, used to switch algorithms dynamically.
• Decorator is like adding toppings to pizza ■, Strategy is like choosing how to cook it ■.