
Master Java design patterns introduces creational, structural, and behavioral patterns with examples like factory, singleton, adapter, and iterator, plus prerequisites, setup for IntelliJ and JDK, and downloadable materials.
Discover the factory design pattern within creational patterns for Java design patterns, and learn how object creation is decoupled from usage to improve flexibility.
Explore the factory design pattern, centralizing object creation via a factory class and a factory method to decide objects at runtime, with examples in shapes, payment processors, and notifications.
Use the factory design pattern to create notification objects (email, SMS, WhatsApp) via a centralized factory, so the client calls notify user without handling creation details.
Create a Java project and implement the factory design pattern with a notification service, featuring email and sms notifications, to illustrate an initial implementation and setup for creational design patterns.
Implement a factory design pattern style notification service routing email, SMS, or WhatsApp by type, with an explicit if-else dispatch and a plan to refactor.
Implement the factory design pattern to create notification types (email, SMS, WhatsApp) via a notification interface, moving from initial code to a dedicated factory package.
Implement a notification factory that creates email, SMS, or WhatsApp notifications based on type, with error checks and an enhanced switch, centralizing object creation and easing client code.
Create a client app that uses a notification factory to instantiate email, SMS, and WhatsApp notifications, demonstrating the factory design pattern and testing unknown push type to trigger an exception.
Explore the abstract factory design pattern to build related object families via interfaces, enabling UI component factories with platform specific components and interchangeable providers while keeping a consistent API.
Learn the abstract factory design pattern by implementing email and SMS notification components, including user and admin variants, interfaces, and basic UML diagrams in a hands-on coding session.
Implement a notification factory using the abstract factory pattern by building a notification factory interface and concrete user and admin factories that create email and SMS notifications.
Set up the main application using the abstract factory pattern to build user and admin notification components via dedicated factories, creating email and SMS notifications through interfaces.
Master the singleton design pattern by creating a single shared instance with a private constructor and a static getInstance method, and explore uses in logger, runtime, and Spring beans.
Implement a singleton with lazy initialization, using a private constructor and a static instance accessed via a get instance method. Test confirms the same shared logger instance across calls.
Demonstrates eager initialization of a singleton by creating the single instance at class load time, sharing one logger across the eager package and the main app.
Make the singleton thread-safe by converting the getInstance method to a synchronized static method, enabling lazy initialization and ensuring only one instance is created in a multithreaded environment.
The Bill Pugh singleton implements lazy initialization and thread safety with a static inner helper class, avoiding synchronization overhead and providing a single instance via getInstance.
Master the builder design pattern to construct complex objects step by step with a fluent, chainable api that yields immutable objects, illustrated by meal app, Java locale, and OpenAI sdk.
Explore the builder design pattern via a meal example, focusing on the static inner meal builder, fluent burger, drinks, and fries methods, and the build sequence.
Explore the builder pattern by creating enums for burger, drink, and fries and defining a meal class with a required burger and optional drink and fries fields.
Implement the meal builder's static inner class with a required burger and optional drink and fries, using Objects.requireNonNull and fluent setter methods for chaining.
Make the meal constructor private to accept a builder and implement build to return a new meal, overriding toString and providing getters for burger, drink, and fries to ensure immutability.
Review the meal class and its static builder, define burger, drink, and fries, use a fluent API to set drink and fries, then build and retrieve values.
Showcases building a meal with the builder pattern, using a required burger and an optional drink. Demonstrates sequencing, printing meal outputs, and testing the main app with optional fries.
Refactor the two string method for null handling. Use a reusable display value helper with Objects.toString to default to none, applying to drink and fries within the builder design pattern.
Master the prototype design pattern by cloning a base object instead of using the new keyword, then customize instances; illustrated with video game characters, data analytics reports, and email newsletters.
Explore the prototype design pattern by implementing Java's clonable interface, overriding a public clone method, and creating a cloneable email template with toString and getter/setter methods.
Explore the prototype design pattern by cloning a base email template to create group and individual emails, customize subjects, and efficiently generate objects.
Explore structural design patterns with the adapter pattern, unifying incompatible APIs through a common interface while decoupling client code from providers like Stripe and PayPal.
Explore the adapter design pattern with a unified payment processor interface and implement adapters for PayPal and Stripe to convert calls for different APIs, currencies, and data formats.
Define a common payment processor interface with a pay method using BigDecimal, and a payment service that remains unaware of adapters for loose coupling and future PayPal and Stripe adapters.
Develop a demo in-house payment processor with a direct interface implementation, set up a main app and payment service to illustrate the adapter pattern and future Stripe and PayPal integrations.
The lecture demonstrates implementing the adapter design pattern to connect an app to a mock PayPal SDK, translating its amount and currency into the SDK's expected inputs.
Implement a PayPal adapter by bridging the app with the PayPal SDK, converting BigDecimal amounts and currency codes, and delegating payments through a payment processor.
Explore the final step of building a Stripe adapter that converts dollars and cents into total cents for a mock Stripe SDK, adapting to an incompatible method signature.
Implement a stripe adapter that converts a big decimal to cents with two decimals and rounding halfway up, bridging the app with the stripe SDK through the adapter pattern.
Explore the bridge design pattern to decouple abstraction from implementation using composition, preventing class explosion and enabling independent evolution of payment methods and currencies.
Explore the bridge design pattern through a payment system that supports multiple methods and currencies, with payments delegating to USD and euro currency processors.
Implement the bridge design pattern by creating a currency processor interface with a pay(amount) method and a euro currency processor that formats the payment amount using a locale-specific euro symbol.
Explore the bridge design pattern by implementing a net banking payment that delegates to a currency processor, connects to a bank API, and processes a given amount.
Explore the bridge design pattern in coding by implementing a net banking payment using a euro currency processor, demonstrating abstraction and implementation separation.
Utilize the bridge design pattern where a credit card payment delegates to a USD currency processor, authorizes the card through a simulated gateway, formats in USD, and displays the amount.
Demonstrate the bridge design pattern by delegating credit card payment to a currency processor, using USD as the implementation and formatting the amount with a currency symbol.
Explore the decorator design pattern to add responsibilities to objects dynamically, using abstract and concrete decorators in coffee, data source, and notification examples.
Explore the decorator design pattern by adding priority, signature, and uppercase decorators to a notification system, chaining them to modify messages before delegating to the base notification.
Refactor notifications to accept a string message within a new decorator package, illustrating the decorator design pattern, and update email, SMS, and WhatsApp notifications to pass runtime messages.
Learn how to implement the decorator design pattern by building a notification decorator, a priority decorator, and integrating them in the main app to send priority emails.
Learn how to implement the decorator design pattern by adding an uppercase decorator that wraps a notification, overriding notify user to emit uppercase messages, demonstrated with sms and a factory.
Learn to implement the decorator design pattern by adding a signature decorator that appends a footer to messages, wrapping WhatsApp notifications without modifying the original code.
Chain multiple decorators—priority, uppercase, and signature—through a WhatsApp notification to demonstrate the decorator design pattern in action.
Explore the composite design pattern by modeling hierarchies as tree structures with leaves and composites, using a uniform component interface to treat files, folders, and tasks recursively.
Master the composite design pattern with a file system example, where files are leaves and folders are composites that delegate get size and print recursively, with UML and sequence diagrams.
Define a file system component interface with get name and get size, then implement a leaf file class in the composite pattern.
Create the composite folder in a file system by implementing the file system component interface, storing a name and child components, and delegating to children to recursively accumulate size.
In this coding demo, a main app builds a composite structure of folders and files, aggregates sizes from files, and prints folder sizes to illustrate the composite design pattern.
Implement the composite design pattern by adding a print method with indentation to file and folder components, recursively printing child components and calculating sizes.
Learn how the composite design pattern handles zip archives as leaf components by implementing a Zipfile with a compressed size based on a compression ratio, supporting extensibility.
Demonstrates extending the composite structure by adding a zip file as a new file system component, calculating compressed size, and integrating into folders without changing main logic.
Master the facade design pattern that provides a unified interface to subsystems, delegates requests, and decouples clients to simplify code through a facade class.
Explore the facade design pattern through a travel booking app, where the trip planner facade coordinates flights, hotels, and payments via value objects like trip request and trip confirmation.
Explore step one of building a facade-based value object layer for a trip booking system by modeling trip request and trip confirmation as Java records, reducing boilerplate and ensuring immutability.
Create the flight booking subsystem for the trip planner facade, using a trip request record to extract origin, destination, dates, and guests and generate a uuid confirmation.
Implement the hotel booking service as a subsystem invoked by the trip planner facade to handle reservations, extracting destination, check-in and check-out dates, and guests, and returning UUID-based booking reference.
Create a payment service as a subsystem used by the trip planner facade, charge the trip with last four card digits, origin, destination, and return a pm uuid reference.
Build a trip planner facade that coordinates flight booking, hotel booking, and payments under a single interface, then implement book complete trip to return a trip confirmation with a uuid.
Create a trip planner facade to simplify booking and coordinate flight, hotel, and payment services. Build a dynamic trip request and generate a trip confirmation via the facade.
implement a pretty-printed trip confirmation in a java app using the facade design pattern, formatting trip id, flight, hotel, and payment on separate lines.
Explore behavioral design patterns that manage object interaction and communication, reduce tight coupling, and simplify logic, with examples like message filtering pipeline, GPS navigation application, and call center routing.
Learn how the chain of responsibility decouples a request from its receivers by passing it through a chain of filters, such as authentication, logging, and compression.
Explore a chain of responsibility in a message filtering pipeline that authenticates, logs, and compresses a payload via a filter interface with set next and apply.
Create a request class with payload, authenticated, logged, and compressed fields, then define a chain of responsibility filter interface with setNext and apply to process the request.
Explore the chain of responsibility pattern by implementing auth, logging, and compression filters, handling authentication in the apply method, and forwarding to the next filter or terminating the chain.
Demonstrates chain of responsibility design pattern by implementing a log filter and a compression filter that log requests, mark them as compressed, and delegate to the next filter via apply.
Define the filter chain order for the chain of responsibility and implement auth, log, and compression filters. Kick off a request, pass authentication, and observe the final processed state.
Demonstrate how the chain of responsibility stops processing when authentication fails by using a request without the word auth, preventing logging and compression filters from running.
Refactors the chain of responsibility to use a flexible attributes map, decoupling request state from filters and preserving attribute order with a linked hash map.
Demonstrates extending a chain of responsibility by adding a trim filter after auth to remove leading and trailing spaces from payloads, showing flexible, loosely coupled filtering.
Master the iterator design pattern to traverse collections without exposing internal structure, using a standard interface with hasNext and next, enabling flexible traversal across schedules, playlists, and catalogs.
Explore the iterator design pattern with a course catalog, implementing an iterator interface and a concrete course iterator to traverse and display courses using hasNext and next.
Define a course class with a name field and standard accessors, then define a generic iterator interface with hasNext and next to enable traversing any collection type.
Develop a concrete iterator for the course list, implementing hasNext and next to traverse courses, track an index, and throw NoSuchElementException when no more elements remain.
Define the course catalog as an aggregate collection that stores course objects, adds courses, and returns a course iterator to traverse the collection.
Learn the iterator design pattern by implementing a main app that traverses a course catalog using a generic iterator to print course names without revealing the collection's structure.
Implement a reverse course iterator to display the most recently added courses first, enabling a what's new feature and reverse chronological order in the course catalog.
Explore the observer design pattern as a one-to-many, decoupled notification system where a subject broadcasts updates to observers that react independently, with examples like shipments, stock tickers, and game scores.
Learn how the observer pattern uses a scoreboard server to broadcast score updates to the jumbotron, mobile app, and Discord bot observers via register, notify, and unsubscribe.
Define the score observer interface and score subject interface in an observer package. Implement updateScore with home and away scores, register and remove observers, and notify observers on score changes.
Develop a concrete subject in the game scoreboard server that holds home and away scores and notifies observers on updates, using a linked hash set to track observers.
Implement concrete observers for the observer pattern, building a jumbotron stadium display and a mobile app display that react to score updates via the score observer interface.
Set up the game scoreboard server, register the jumbotron and mobile app observers, simulate score changes, and demonstrate unsubscription behavior as subscribers come and go.
Implement a Discord sports bot as a concrete observer to post home and away scores to a channel, register it with the app, and demonstrate adding observers without code changes.
Master the strategy design pattern by exchanging families of algorithms at runtime, decoupling behavior from clients, and applying it to shipping cost calculation, route planning, and the course catalog sorter.
Explore the strategy design pattern with a course catalog sorter, implementing sort strategies for name, rating, and student count, and switching strategies at runtime through the course sorter.
Apply the strategy design pattern by implementing a concrete name sort strategy with a custom name comparator to sort courses alphabetically in ascending order.
Implement the course sorter as a context that delegates course sorting to a strategy, enabling runtime changes with a non-null checked constructor and a setter to swap strategies.
Develop the main app as the client to demonstrate the strategy pattern by sorting three courses with a name sort strategy, and switch sorting strategies at runtime.
Refactor the strategy pattern implementation to use method references for sorting, introducing v1 and v2 packages to compare old inner-class comparators with modern Java techniques.
Implement concrete strategies for rating sorting and student-count sorting, use comparators and method references, and switch strategies at runtime to sort courses by rating or number of enrolled students.
Apply the strategy design pattern to add a sort direction enum and implement descending and ascending order for name, rating, and student count sorts, using a reversed comparator when descending.
Refine strategy design pattern implementations by adding sort direction to rating and student count strategies, refactoring with constructors, extracting comparators, and enforcing ascending defaults.
Add sort direction to the strategy design pattern, enabling ascending and descending rating and student count sorts, with prints and outputs demonstrating the integration.
Apply the strategy design pattern to chain sorts: sort courses by student count first, then by rating as a tiebreaker, using a composite comparator.
Apply the strategy design pattern to chain sorting criteria by student count and rating, observe tiebreakers, and implement ascending and descending orders.
Refactor the strategy design pattern by removing an incorrect sword strategy and replacing autoboxing with comparing int and comparing double for primitives, improving readability of rating and student count sorts.
Explore the template design pattern by defining a template method in a base class, with abstract steps overridden by subclasses, moving duplicate code and preserving the workflow.
Examine the template design pattern to remove duplication in the course catalog sorter by moving common sorting logic to an abstract sort strategy and letting concrete strategies implement get comparator.
Students learn to implement the template design pattern by creating an abstract sort strategy with a getComparator template method, refactoring common logic, and defining direction handling in Java.
Refactor existing strategies using the template method getComparator in the name sort strategy. Extend the abstract sort strategy, sort courses by name with comparator.comparing, and clean up imports.
Refactor the rating and student count sort strategies within the template design pattern by extending abstract sort strategy, removing duplicates, and overriding the get comparator method with comparator.comparingDouble(course.getRating) and comparator.comparingInt(course.getStudentCount).
Complete the template design pattern by finalizing the student count and rating sort strategies and testing the main app’s sorting by name, course name, rating, and students.
Explore the memento design pattern to capture an object state with snapshots, enabling undo and restoration while preserving encapsulation, using caretakers and originators. See editor, game, and query history examples.
Master the command design pattern to encapsulate requests as objects and decouple invokers from receivers. See how queuing, logging, and undo support emerge in real-world apps.
Learn the command design pattern through a smart home example, binding light and thermostat receivers to light on, light off, and thermostat set commands, with a remote control as invoker.
Define the command design pattern smart home command interface and establish the contract for all commands with execute, undo, and get description methods in a new command package.
Develop receivers for the command design pattern by implementing light and thermostat classes in Java, including constructors, getters, setters, and on/off and set temperature methods with console outputs.
Explore the command design pattern by implementing concrete light on and light off commands with execute and undo actions, plus outlining a thermostat set command in a smart home.
Implement a concrete command for the command design pattern that sets a thermostat to a target temperature in Celsius, stores the previous temperature on execute, and restores it on undo.
Develop the remote control invoker by implementing press button and undo using a history deck, executing commands via the smart home command interface, and printing history.
Demonstrates the command pattern in a main app by creating a living room light and a remote control invoker, issuing on and off commands, and printing the command history.
Apply the command design pattern to a thermostat demo, executing set and undo commands via remote to move from 18 to 22 degrees, and fix a print line shadowing bug.
Add a new pet food dispenser as the receiver and implement a concrete command to dispense a single serving, using the smart home command interface, noting undo is unavailable.
Examine how the command design pattern orchestrates a pet food dispenser via a remote control, executing commands and handling undo limitations in a smart home demo.
Create and use macro commands to group multiple commands into a single named scene, execute them in order, and undo in reverse order using a list and for loop.
Turn on the office and bedroom lights and set thermostat to 21 with one button press, using a macro. Undo in reverse order to demonstrate the command design pattern.
explore the mediator design pattern that uses a mediator to decouple interacting objects, reducing spaghetti code and improving maintainability, with examples like air traffic control, booking coordinators, and ticket routing.
Understand the mediator design pattern via a support ticket routing example, where billing and technical services communicate through a concrete mediator called the support center, centralizing all communication.
Define models for the mediator pattern by creating an issue type enum (billing, technical) and a ticket domain object with type, message, and customer name, plus a constructor and getters.
Define mediator and colleague interfaces for the mediator design pattern and implement concrete billing and technical services as colleagues. Implement the support service interface to handle tickets.
Explore how adding a supporting NotificationSender enhances the mediator design pattern by sending a confirmation after a ticket is processed, illustrating routing and handling messages in the support center.
Routes tickets to technical or billing services, registers new services, and sends confirmations via the concrete mediator called the support center.
wire a mediator-driven client app by wiring a support center to route billing and technical tickets, send notifications, and print results, demonstrating loose coupling and centralized routing.
Learn how the interpreter design pattern replaces messy conditional logic with a parser and expression objects to interpret commands such as join, mute, and remind, enabling clean, scalable rule-based logic.
Explore the interpreter design pattern by modeling commands as expressions, with concrete expressions like join, mute, and remind, a chat context, and a command parser that builds expressions at runtime.
Implement the interpreter design pattern by adding concrete terminal expressions for the remind command and the invalid command, including reminder creation messages and unrecognized command errors.
Develop a command parser for the interpreter pattern that parses raw input into a command and arguments, returning join, mute, or remind expressions or an invalid command expression.
Develop a client that demonstrates the interpreter design pattern by parsing chat commands, interpreting expressions, and executing actions like join, mute, and remind within a shared chat context.
This lecture demonstrates enhancing interpreter design pattern by refactoring the interpret method to return boolean, updating join, mute, remind to true, and invalid command to false, with v1 and v2.
Implement the and expression as a non-terminal node in the interpreter pattern, combining left and right expressions, and update the parser to recursively build the expression tree.
Explore enhancements to the interpreter design pattern by chaining and expression commands on one line, parsing into separate join and remind expressions, and processing them recursively in a Java app.
Wrap up this course on Java design patterns by reviewing creational, structural, and behavioral patterns, then download your certificate, share it on social media, and rate the course.
Master the Design Patterns Every Java Developer Should Know ... with Hands-On Projects, Live Coding, and Real-World Examples
This course covers the most essential Java Design Patterns, based on the classic Gang of Four (GoF) book. These patterns are brought to life with modern Java and explained in a clear, practical, and easy-to-follow way.
You'll learn how to use Factory, Singleton, Builder, Adapter, Facade, Iterator, Strategy, Command and more, all while applying development techniques to improve your code quality.
We go beyond theory.
You’ll build real Java applications using each pattern so you understand how and when to use them in real-world development.
Just like my bestselling Spring Boot courses (over 900,000+ students, 82,000+ reviews, #1 on Udemy), I guide you step-by-step, explaining every line of code we write ... from scratch.
What You’ll Learn
The 3 main types of design patterns: Creational, Structural, Behavioral
Creational Patterns like Factory, Singleton, Builder, Prototype and Abstract Factory
Structural Patterns like Adapter, Bridge Composite, Facade and Decorator
Behavioral Patterns like Chain, Iterator, Observer and Strategy
Real-world Java applications built using best practices
What You Get
Over 9+ hours of HD video
All source code and project files available for download
PDFs of all lecture slides
Closed captions in English
Hands-On Learning Experience
You’ll type in every line of code with me ... no copy/paste programming
Live coding in IntelliJ using modern Java. We use the IntelliJ free version.
Full source code and project files included
All lectures come with downloadable PDF notes for quick review
Course Outline
Section: Creational Design Patterns
Patterns that focus on object creation mechanisms.
Factory Method Pattern
Abstract Factory Pattern
Singleton Pattern
Builder Pattern
Prototype Pattern
Section: Structural Design Patterns
Patterns that focus on class and object composition.
Adapter Pattern
Bridge Pattern
Decorator Pattern
Composite Pattern
Facade Pattern
Section: Behavioral Design Patterns
Patterns that focus on communication and responsibilities between objects.
Chain of Responsibility Pattern
Iterator Pattern
Observer Pattern
Strategy Pattern
Template Method Pattern
Memento Pattern
State Pattern
Visitor Pattern
Command Pattern
Mediator Pattern
Interpreter Pattern
Student Praise from My Other Courses
“Best structure and teaching method I've ever seen. You make every concept easy to understand.” – Dave Z.
“The best Java instructor on Udemy. Bar none.” – Muzi P.
“Real-world, industry-ready examples. Worth every penny.” – Premang
“You are the gold standard for teaching software development.” – Julie H.
No Risk – Udemy 30-Day Money Back Guarantee
If you're not satisfied, Udemy offers a full refund. No questions asked.
Join 900,000+ Java developers already learning with me on Udemy.
Let’s master Java Design Patterns together and take your coding skills to the next level.
Tools & Technologies
Java 25+ (works with Java 17+)
IntelliJ IDEA (free version)
Maven (for dependency management)
We are Responsive Instructors
Got a question? We respond to all questions within 24 hours.
You're never learning alone. We're here to help you every step of the way.
Who Is This Course For?
Java developers of all levels who want to improve their design and architecture skills
Anyone preparing for technical interviews (design questions are common!)
Developers who want to build scalable, reusable, and clean Java applications
Software engineers looking to apply industry-standard patterns in real projects