Lesson Completion
Back to course

Module 19: Design Patterns

Overview

This module covers essential design patterns in Java, including creational, structural, and behavioral patterns. Learn how to solve common design problems using proven solutions and best practices.

Learning Objectives

  • Understand design pattern concepts and categories
  • Master creational design patterns
  • Learn structural design patterns
  • Implement behavioral design patterns
  • Apply SOLID principles
  • Recognize when to use each pattern
  • Avoid anti-patterns

Topics Covered

19.1 Introduction to Design Patterns

19.1.1 What are Design Patterns?

  • Reusable Solutions
  • Best Practices
  • Common Problems
  • Design Experience
  • Gang of Four (GoF)

19.1.2 Benefits of Design Patterns

  • Code Reusability
  • Communication
  • Proven Solutions
  • Flexibility
  • Maintainability

19.1.3 Pattern Categories

  • Creational Patterns
  • Structural Patterns
  • Behavioral Patterns
  • Architectural Patterns

19.1.4 Pattern Elements

  • Name
  • Problem
  • Solution
  • Consequences

19.2 SOLID Principles

19.2.1 Single Responsibility Principle (SRP)

  • One Reason to Change
  • Cohesion
  • Class Design
  • Examples

19.2.2 Open/Closed Principle (OCP)

  • Open for Extension
  • Closed for Modification
  • Abstraction
  • Examples

19.2.3 Liskov Substitution Principle (LSP)

  • Substitutability
  • Behavioral Subtyping
  • Inheritance Rules
  • Examples

19.2.4 Interface Segregation Principle (ISP)

  • Small, Focused Interfaces
  • Client-Specific Interfaces
  • No Fat Interfaces
  • Examples

19.2.5 Dependency Inversion Principle (DIP)

  • Depend on Abstractions
  • High-Level vs Low-Level
  • Decoupling
  • Examples

19.3 Creational Patterns

19.3.1 Singleton Pattern

  • Single Instance
  • Global Access Point
  • Implementation Approaches
    • Eager Initialization
    • Lazy Initialization
    • Thread-Safe Singleton
    • Bill Pugh Singleton
    • Enum Singleton
  • Use Cases
  • Drawbacks

19.3.2 Factory Method Pattern

  • Define Interface for Object Creation
  • Subclass Decides Implementation
  • Virtual Constructor
  • Use Cases
  • Implementation

19.3.3 Abstract Factory Pattern

  • Family of Related Objects
  • Factory of Factories
  • Product Families
  • Use Cases
  • Implementation

19.3.4 Builder Pattern

  • Complex Object Construction
  • Step-by-Step Building
  • Fluent Interface
  • Immutable Objects
  • Use Cases
  • Implementation

19.3.5 Prototype Pattern

  • Clone Objects
  • Object Copying
  • Shallow vs Deep Copy
  • Cloneable Interface
  • Use Cases
  • Implementation

19.4 Structural Patterns

19.4.1 Adapter Pattern

  • Interface Conversion
  • Wrapper Pattern
  • Legacy Code Integration
  • Class vs Object Adapter
  • Use Cases
  • Implementation

19.4.2 Bridge Pattern

  • Decouple Abstraction from Implementation
  • Two Hierarchies
  • Runtime Binding
  • Use Cases
  • Implementation

19.4.3 Composite Pattern

  • Tree Structure
  • Part-Whole Hierarchy
  • Uniform Treatment
  • Recursive Composition
  • Use Cases
  • Implementation

19.4.4 Decorator Pattern

  • Add Responsibilities Dynamically
  • Alternative to Subclassing
  • Wrapper Objects
  • Flexible Extension
  • Use Cases (I/O Streams)
  • Implementation

19.4.5 Facade Pattern

  • Simplified Interface
  • Subsystem Access
  • Reduce Complexity
  • Unified Interface
  • Use Cases
  • Implementation

19.4.6 Flyweight Pattern

  • Share Objects
  • Memory Optimization
  • Intrinsic vs Extrinsic State
  • Object Pool
  • Use Cases (String Pool)
  • Implementation

19.4.7 Proxy Pattern

  • Surrogate Object
  • Control Access
  • Types of Proxies
    • Virtual Proxy
    • Protection Proxy
    • Remote Proxy
    • Smart Proxy
  • Use Cases
  • Implementation

19.5 Behavioral Patterns

19.5.1 Chain of Responsibility Pattern

  • Request Handler Chain
  • Decoupling Sender/Receiver
  • Multiple Handlers
  • Use Cases (Logging, Event Handling)
  • Implementation

19.5.2 Command Pattern

  • Encapsulate Request
  • Parameterize Objects
  • Queue Operations
  • Undo/Redo
  • Use Cases
  • Implementation

19.5.3 Iterator Pattern

  • Sequential Access
  • Traverse Collection
  • Hide Internal Structure
  • Java Iterator Interface
  • Use Cases
  • Implementation

19.5.4 Mediator Pattern

  • Centralized Communication
  • Reduce Coupling
  • Colleague Objects
  • Use Cases (Chat Room)
  • Implementation

19.5.5 Memento Pattern

  • Capture Object State
  • Restore State
  • Undo Mechanism
  • Encapsulation
  • Use Cases
  • Implementation

19.5.6 Observer Pattern

  • One-to-Many Dependency
  • Event Notification
  • Publisher-Subscriber
  • Java Observer/Observable
  • Use Cases (MVC, Event Listeners)
  • Implementation

19.5.7 State Pattern

  • Object Behavior Changes with State
  • State Machine
  • State Transitions
  • Context and State
  • Use Cases
  • Implementation

19.5.8 Strategy Pattern

  • Encapsulate Algorithms
  • Runtime Selection
  • Family of Algorithms
  • Composition over Inheritance
  • Use Cases (Sorting, Comparator)
  • Implementation

19.5.9 Template Method Pattern

  • Algorithm Skeleton
  • Subclass Steps
  • Hollywood Principle
  • Hook Methods
  • Use Cases
  • Implementation

19.5.10 Visitor Pattern

  • Operations on Object Structure
  • Double Dispatch
  • Adding Operations
  • Element Traversal
  • Use Cases
  • Implementation

19.5.11 Interpreter Pattern

  • Language Grammar
  • Parse and Interpret
  • Abstract Syntax Tree
  • Use Cases (Regular Expressions)
  • Implementation

19.6 Architectural Patterns

19.6.1 MVC (Model-View-Controller)

  • Separation of Concerns
  • Model: Data and Logic
  • View: Presentation
  • Controller: Input Handling
  • Use Cases
  • Implementation

19.6.2 MVP (Model-View-Presenter)

  • MVC Variation
  • Testability
  • Passive View
  • Use Cases
  • Implementation

19.6.3 MVVM (Model-View-ViewModel)

  • Data Binding
  • Separation of UI and Logic
  • Modern UI Frameworks
  • Use Cases
  • Implementation

19.6.4 Repository Pattern

  • Data Access Abstraction
  • Collection-Like Interface
  • Centralized Data Access
  • Use Cases
  • Implementation

19.6.5 DAO (Data Access Object)

  • Database Access Layer
  • Abstract Persistence
  • CRUD Operations
  • Use Cases
  • Implementation

19.6.6 Dependency Injection

  • Inversion of Control
  • Constructor Injection
  • Setter Injection
  • Field Injection
  • DI Containers (Spring)
  • Use Cases

19.7 Concurrency Patterns

19.7.1 Thread Pool Pattern

  • Worker Threads
  • Task Queue
  • Resource Management
  • ExecutorService
  • Use Cases

19.7.2 Producer-Consumer Pattern

  • Queue-Based Communication
  • BlockingQueue
  • Thread Coordination
  • Use Cases
  • Implementation

19.7.3 Read-Write Lock Pattern

  • Multiple Readers
  • Exclusive Writer
  • ReadWriteLock
  • Use Cases
  • Implementation

19.7.4 Future Pattern

  • Asynchronous Result
  • Callback Mechanism
  • Future and CompletableFuture
  • Use Cases
  • Implementation

19.8 Enterprise Patterns

19.8.1 Service Locator Pattern

  • Service Registry
  • Centralized Lookup
  • Dependency Management
  • Use Cases

19.8.2 Business Delegate Pattern

  • Business Tier Abstraction
  • Client-Service Decoupling
  • Remote Access
  • Use Cases

19.8.3 Transfer Object Pattern

  • Data Transfer Object (DTO)
  • Serialize Data
  • Reduce Network Calls
  • Use Cases

19.8.4 Front Controller Pattern

  • Centralized Request Handling
  • Web Applications
  • Dispatch Mechanism
  • Use Cases (Servlet Filters)

19.9 Functional Patterns (Java 8+)

19.9.1 Function Composition

  • Combining Functions
  • andThen(), compose()
  • Pipeline Processing
  • Use Cases

19.9.2 Monads (Optional, Stream)

  • Functional Wrappers
  • Chain Operations
  • Null Safety
  • Use Cases

19.9.3 Lazy Evaluation

  • Deferred Computation
  • Supplier
  • Stream Operations
  • Use Cases

19.10 Anti-Patterns

19.10.1 God Object

  • Too Many Responsibilities
  • Lack of Cohesion
  • Maintenance Issues
  • How to Avoid

19.10.2 Spaghetti Code

  • No Structure
  • Tangled Dependencies
  • Hard to Maintain
  • How to Avoid

19.10.3 Golden Hammer

  • Using One Solution for Everything
  • Over-Application
  • Inappropriate Usage
  • How to Avoid

19.10.4 Premature Optimization

  • Optimizing Too Early
  • Complexity without Benefit
  • Measure First
  • How to Avoid

19.10.5 Circular Dependencies

  • Modules Depend on Each Other
  • Tight Coupling
  • Hard to Test
  • How to Avoid

19.11 Pattern Selection

19.11.1 When to Use Patterns

  • Common Problems
  • Proven Solutions
  • Team Communication
  • Not Every Problem

19.11.2 Pattern Relationships

  • Complementary Patterns
  • Alternative Patterns
  • Pattern Combinations

19.11.3 Pattern vs Simplicity

  • Balance Complexity
  • YAGNI Principle
  • Refactor to Patterns
  • Know When Not to Use

19.12 Patterns in Java Libraries

19.12.1 Collections Framework

  • Iterator Pattern
  • Decorator Pattern
  • Factory Pattern
  • Strategy Pattern

19.12.2 I/O Streams

  • Decorator Pattern
  • Adapter Pattern
  • Chain of Responsibility

19.12.3 JDBC

  • Bridge Pattern
  • Factory Pattern
  • Singleton Pattern

19.12.4 Concurrency API

  • Factory Pattern
  • Executor Pattern
  • Future Pattern

19.13 Design Pattern Best Practices

19.13.1 Understanding Before Using

  • Learn the Intent
  • Know the Trade-offs
  • Context Matters
  • Don't Force Patterns

19.13.2 Naming Conventions

  • Pattern Name in Class Name
  • Clear Intent
  • Documentation
  • Team Understanding

19.13.3 Testing Patterns

  • Unit Testing
  • Mock Objects
  • Dependency Injection
  • Testability

19.14 Modern Java Patterns

19.14.1 Functional Patterns

  • Lambda Expressions
  • Method References
  • Stream API
  • Function Composition

19.14.2 Reactive Patterns

  • Observer Pattern Evolution
  • Reactive Streams
  • Backpressure
  • Event-Driven

19.14.3 Microservices Patterns

  • Service Discovery
  • Circuit Breaker
  • API Gateway
  • Event Sourcing

Hands-on Exercises

  1. Implement Singleton pattern variations
  2. Create Factory and Abstract Factory
  3. Build Builder pattern for complex objects
  4. Implement Decorator pattern (I/O example)
  5. Create Observer pattern (event system)
  6. Implement Strategy pattern (sorting)
  7. Build Command pattern (undo/redo)
  8. Create Adapter pattern (legacy integration)
  9. Implement Chain of Responsibility
  10. Build State pattern (state machine)
  11. Create Template Method pattern
  12. Implement MVC architecture

Key Takeaways

  • Patterns provide proven solutions
  • SOLID principles guide design
  • Not all problems need patterns
  • Patterns improve communication
  • Balance simplicity and flexibility
  • Refactor to patterns when needed
  • Understand trade-offs
  • Patterns evolve with language

Common Mistakes to Avoid

  • Overusing patterns
  • Forcing patterns inappropriately
  • Not understanding intent
  • Cargo cult programming
  • Ignoring SOLID principles
  • Premature pattern application
  • Wrong pattern selection
  • Not considering alternatives

Real-World Applications

  • Framework design
  • Enterprise applications
  • API design
  • Library development
  • Game development
  • Web applications
  • Microservices
  • Mobile applications

Additional Resources

  • Design Patterns: Elements of Reusable OO Software (GoF)
  • Head First Design Patterns
  • Effective Java (Patterns)
  • Refactoring to Patterns
  • Java Design Patterns by Baeldung

Assessment

  • Quiz on design patterns
  • Practical: Implement various patterns
  • Pattern identification exercises
  • Refactoring challenges
  • Design pattern selection scenarios
  • Anti-pattern identification

Previous Module

Module 18: Memory Management

Next Module

Module 20: Best Practices and Coding Standards