Design Patterns - Study Notes
1. Overview
Definition: General solutions for common software design problems. Not direct code, but
reusable templates.
Purpose: Simplify development, improve reusability and maintainability, and encourage
best practices.
2. Benefits of Design Patterns
Proven solutions to recurring problems.
Improve code structure and readability.
Enhance collaboration by following standard approaches.
3. Components of a Pattern
Intent: Describes the problem and solution.
Motivation: Explains why the pattern exists.
Structure: Diagram showing relationships.
Code Example: Implementation in a programming language.
4. Types of Patterns
1. Creational Patterns
Focus: Object creation mechanisms.
Examples:
o Factory Method
o Builder
o Singleton
2. Structural Patterns
Focus: Object and class composition.
Examples:
o Adapter
o Decorator
3. Behavioral Patterns
Focus: Communication between objects.
Examples:
o Observer
o Strategy
5. Key Patterns
5.1 Factory Method
Purpose: Replace direct object creation with factory methods.
Example:
o Abstract Class: Logistics.
o Subclasses: RoadLogistics (returns Truck), SeaLogistics (returns Ship).
Benefits: Adds new types of logistics without modifying existing code.
5.2 Builder
Purpose: Step-by-step construction of complex objects.
Example:
o HouseBuilder builds houses with various features.
Benefits: Avoids large constructors and unnecessary parameters.
5.3 Singleton
Purpose: Ensures a class has only one instance.
Use Case: Database connections, configuration management.
Key Idea: Private constructor and static access method.
5.4 Adapter
Purpose: Converts one interface into another.
Example:
o Converts XML data into JSON for a third-party library.
Benefits: Enables compatibility between incompatible systems.
5.5 Decorator
Purpose: Adds new functionality dynamically.
Example:
o A Coffee object can have decorators like Milk or Chocolate.
Benefits: Flexible extension of object behavior.
5.6 Observer
Purpose: Establishes a subscription mechanism.
Example:
o A Customer subscribes to a Store for product updates.
Benefits: Reduces unnecessary checks and spam notifications.
5.7 Strategy
Purpose: Encapsulates algorithms for interchangeability.
Example:
o A football match has strategies like Attack or Defend.
Benefits: Simplifies algorithm management and reduces code duplication.
6. Comparison Table
Pattern Category Purpose Example
Factory Method Creational Flexible object creation Logistics app with Truck and Ship
Step-by-step object
Builder Creational Building customizable House objects
construction
Singleton Creational Single instance enforcement Database connection
Adapter Structural Interface compatibility XML to JSON conversion
Decorator Structural Adding behavior dynamically Coffee with Milk or Chocolate
Customers subscribed to store
Observer Behavioral Subscription-based notification
updates
Strategy Behavioral Algorithm interchangeability Football match strategies