Practical Design Patterns for Java Developers: Hone your software design skills by implementing popular design patterns in Java
By Miroslav Wengner and Bruno Souza
()
About this ebook
Design patterns are proven solutions to standard problems in software design and development, allowing you to create reusable, flexible, and maintainable code. This book enables you to upskill by understanding popular patterns to evolve into a proficient software developer.
You’ll start by exploring the Java platform to understand and implement design patterns. Then, using various examples, you’ll create different types of vehicles or their parts to enable clarity in design pattern thinking, along with developing new vehicle instances using dedicated design patterns to make the process consistent. As you progress, you’ll find out how to extend vehicle functionalities and keep the code base structure and behavior clean and shiny. Concurrency plays an important role in application design, and you'll learn how to employ a such design patterns with the visualization of thread interaction. The concluding chapters will help you identify and understand anti-pattern utilization in the early stages of development to address refactoring smoothly. The book covers the use of Java 17+ features such as pattern matching, switch cases, and instances of enhancements to enable productivity.
By the end of this book, you’ll have gained practical knowledge of design patterns in Java and be able to apply them to address common design problems.
Related to Practical Design Patterns for Java Developers
Related ebooks
Building Your Own JavaScript Framework: Architect extensible and reusable framework systems Rating: 0 out of 5 stars0 ratingsKotlin Quick Start Guide: Core features to get you ready for developing applications Rating: 0 out of 5 stars0 ratingsMy First In Java Rating: 0 out of 5 stars0 ratingsGet Your Hands Dirty on Clean Architecture: Build 'clean' applications with code examples in Java Rating: 0 out of 5 stars0 ratingsJava™ Programming: A Complete Project Lifecycle Guide Rating: 0 out of 5 stars0 ratingsDevOps Revolution: Transforming Software Delivery for High-Performance Teams Rating: 0 out of 5 stars0 ratingsC++ System Programming Cookbook: Practical recipes for Linux system-level programming using the latest C++ features Rating: 0 out of 5 stars0 ratingsLearn Angular: 4 Angular Projects Rating: 0 out of 5 stars0 ratingsThe Art of Modern PHP 8: Learn how to write modern, performant, and enterprise-ready code with the latest PHP features and practices Rating: 0 out of 5 stars0 ratingsMastering C: A Comprehensive Guide to Programming Excellence Rating: 0 out of 5 stars0 ratingsProgramming Constructs in Java Rating: 1 out of 5 stars1/5PrimeFaces Beginner's Guide Rating: 0 out of 5 stars0 ratingsBeginning DotNetNuke Skinning and Design Rating: 0 out of 5 stars0 ratingsAlfresco 3 Cookbook Rating: 0 out of 5 stars0 ratingsData Structures in C / C ++: Exercises and Solved Problems Rating: 0 out of 5 stars0 ratingsNW.js Essentials Rating: 0 out of 5 stars0 ratingsJavaFX 1.2 Application Development Cookbook Rating: 0 out of 5 stars0 ratingsUnlocking the Power of Auto-GPT and Its Plugins: Implement, customize, and optimize Auto-GPT for building robust AI applications Rating: 0 out of 5 stars0 ratingsSimultaneous multithreading A Complete Guide Rating: 0 out of 5 stars0 ratingsVisual Basic for Applications A Complete Guide - 2019 Edition Rating: 0 out of 5 stars0 ratingsJavaScript Concurrency Rating: 0 out of 5 stars0 ratingsUltimate Neural Network Programming with Python Rating: 0 out of 5 stars0 ratingsJava with TDD from the Beginning Rating: 0 out of 5 stars0 ratingsRapid Application Development With CakePHP Rating: 0 out of 5 stars0 ratingsJavaFX in Action Rating: 0 out of 5 stars0 ratings
Enterprise Applications For You
Excel : The Ultimate Comprehensive Step-By-Step Guide to the Basics of Excel Programming: 1 Rating: 5 out of 5 stars5/5QuickBooks 2023 All-in-One For Dummies Rating: 0 out of 5 stars0 ratingsQuickBooks 2024 All-in-One For Dummies Rating: 0 out of 5 stars0 ratingsQuickBooks Online For Dummies Rating: 0 out of 5 stars0 ratingsExcel 101: A Beginner's & Intermediate's Guide for Mastering the Quintessence of Microsoft Excel (2010-2019 & 365) in no time! Rating: 0 out of 5 stars0 ratingsExcel 2019 For Dummies Rating: 3 out of 5 stars3/5Creating Online Courses with ChatGPT | A Step-by-Step Guide with Prompt Templates Rating: 4 out of 5 stars4/5Bitcoin For Dummies Rating: 4 out of 5 stars4/5Access 2019 For Dummies Rating: 0 out of 5 stars0 ratingsSharePoint For Dummies Rating: 0 out of 5 stars0 ratingsExcel Formulas That Automate Tasks You No Longer Have Time For Rating: 5 out of 5 stars5/5Managing Humans: Biting and Humorous Tales of a Software Engineering Manager Rating: 4 out of 5 stars4/5Excel Tips and Tricks Rating: 0 out of 5 stars0 ratingsJIRA 7 Essentials - Fourth Edition Rating: 5 out of 5 stars5/5Notion for Beginners: Notion for Work, Play, and Productivity Rating: 4 out of 5 stars4/5Learning Python Rating: 5 out of 5 stars5/5M Is for (Data) Monkey: A Guide to the M Language in Excel Power Query Rating: 4 out of 5 stars4/5Excel Tables: A Complete Guide for Creating, Using and Automating Lists and Tables Rating: 5 out of 5 stars5/5Enterprise AI For Dummies Rating: 3 out of 5 stars3/5Excel 2019 Bible Rating: 5 out of 5 stars5/5Code like a Pro in C# Rating: 0 out of 5 stars0 ratingsAdopt & Embrace Microsoft Teams: A manager's guide to communication, collaboration, and coordination with Microsoft Teams Rating: 0 out of 5 stars0 ratingsExcel 2016 For Dummies Rating: 4 out of 5 stars4/5
Reviews for Practical Design Patterns for Java Developers
0 ratings0 reviews
Book preview
Practical Design Patterns for Java Developers - Miroslav Wengner
BIRMINGHAM—MUMBAI
Practical Design Patterns for Java Developers
Copyright © 2023 Packt Publishing
All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.
Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing or its dealers and distributors, will be held liable for any damages caused or alleged to have been caused directly or indirectly by this book.
Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.
Group Product Manager: Gebin George
Publishing Product Manager: Kunal Sawant
Senior Editor: Rohit Singh
Technical Editor: Maran Fernandes
Copy Editor: Safis Editing
Project Coordinator: Prajakta Naik
Proofreader: Safis Editing
Indexer: Subalakshmi Govindhan
Production Designer: Prashant Ghare
Marketing Coordinator: Sonia Chauhan
First published: February 2023
Production reference: 1130123
Published by Packt Publishing Ltd.
Livery Place
35 Livery Street
Birmingham
B3 2PB, UK.
ISBN 978-1-80461-467-9
www.packtpub.com
I remember the days when I started exploring the Java platform at Sun Microsystems. It became not only a daily job but also a lifelong hobby and passion. This book is dedicated to my incredible wife, Tanja, my wonderful children, Maxi and Elli, and my entire family for giving me the energy, inspiration, and motivation to keep up the strength needed to complete this book.
– Miroslav Wengner
Foreword
It was November 2021. In a conversation about his developer career, a senior Java developer told me:
I’ve been a senior engineer for almost 20 years. I don’t know what to do to get beyond that level.
That is a typical statement. The length of time varies, but far too many developers and engineers feel stuck in a senior position.
Don’t get me wrong, it’s not bad to be a senior!
You may be working on great projects and using cool technologies. You are probably involved in solving sophisticated problems and facing deep technical challenges.
But there may come a day that you, as the aforementioned developer, feel like you could be doing more in your career, could have more influence in the direction of projects, and have independence and autonomy in your work, or maybe you would feel more fulfilled by inspiring and mentoring other developers.
Although this is something I have heard many times before, that particular instance got me thinking. You see, earlier that same day, I was looking at the results of the Java Community Process (JCP) election. Miroslav Wengner, my friend Miro, had just been elected to the Executive Committee of the premiere standard body of Java technology.
It was impossible not to think about the parallels...
I first met Miro when we worked together on the NetBeans team at Sun Microsystems, the company that created Java. Like the aforementioned developer, Miro had also worked with Java for many years. By the time I had a long conversation with him about his developer career, Miro too had been a senior engineer for a number of years. But he didn’t stop there. Now, just a few years later, Miro has gone way beyond senior: freelancer, speaker, open source developer, committer of the Java Mission Control project at OpenJDK, Java Champion, and JCP EC Member, and why not a book author!
Like Miro, you don’t have to be stuck at the senior level. You too can build your technical reputation, grow beyond senior positions, and have a larger impact on your project, company, and even the world.
All that leads us to this book that you hold in your hands.
What attracted me to Miro’s book is the importance of design patterns in achieving exactly this goal: growing beyond the senior level. Whether you want to become a manager, continue your technical career as a staff-plus engineer, or even if you prefer to be more independent and grow as a freelancer or entrepreneur, you will need to take on more responsibilities and go beyond the code.
Although design patterns are directly connected to code, they are also separate and independent. They encapsulate proven solutions to the common challenges of designing quality software. Design patterns hover above a specific piece of code or even a specific project, and create a common vocabulary for explaining problems and solutions. Anyone in the business of building software should master this vocabulary to understand, communicate, and participate in discussions. After all, growing beyond senior is taking responsibility for your career. You start as a senior in your project, and then you expand your influence by getting involved with more impactful things.
When you master the vocabulary of design patterns, you are more equipped to go beyond your immediate project and get involved in other projects across your company and the industry. You’ll maybe even get to the point of helping define the directions of technology through open source projects and foundations or through standards organizations, like Miro is doing inside the JCP.
This book will help you do exactly that. With a broad view of design patterns applied to the Java ecosystem, you will see not only the concepts and the vocabulary, but also the real implementation and impact of design patterns in software that you use daily.
And one of the things that always impresses me is Miro’s ability to connect software with real things. His open source project, Robo4J, which even won a Duke’s Choice Award, helps you turn your Java code into robots and drones capable of navigating the real world. I was delighted to see Miro taking the same approach to design patterns. The examples in this book, using multiple vehicles and their parts, are written using the latest Java 17+ features, bringing the designs to life and connecting them to real, concrete problems.
So, get started on your journey of building your reputation, growing your career, and reaching beyond the senior level. Knowing design patterns will help you fit right in, speak the language, and participate in the most important decisions. Let the amazing Miro be your guide, and feel free to reach out to me if you would like (as Miro once did) to talk about the next steps in your career.
Bruno Souza
Principal Consultant, Java Champion, JCP Executive Committee Member
@brjavaman
https://java.mn
Contributors
About the author
Miroslav Wengner is an engineer with a passion for resilient distributed systems and product quality. He is a co-author and contributor to the Robo4J project (a reactive soft real-time framework for robotics/IoT). Miro contributes to OpenJDK and participates in other open source technologies. He uses his passion for helping build resilient and scalable solutions.
Miro was selected for the Java Champions Program, recognized as a JavaOne Rockstar, and elected to the Java Community Process (JCP) as an executive committee member.
In addition to his day-to-day duties as a principal engineer at OpenValue, he shares his knowledge at conferences (JavaOne, Devoxx, and so on) and in blogs. Miro believes in the Java ecosystem and helps move it forward!
About the reviewer
Werner Keil works in areas such as Agile, BDD, Cloud-native DevOps, Java, Java EE/Jakarta EE, IoT, security, and microservices, helping Global 500 clients across various industries and IT vendors. Having worked for over 30 years as PM, coach, software architect, and consultant for different sectors, Werner is an Eclipse and Apache Committer and a JCP member in JSRs. Werner has won multiple JCP awards, including Member of the Year and Outstanding Spec Lead, and was recognized as Speaker of All Times by Java2Days, a large Java conference held in eastern Europe. He is an Eclipse Babel Language Champion, a project lead of Eclipse UOMo, and a committer member in the Jakarta EE Specification Committee.
Table of Contents
Preface
Part 1: Design Patterns and Java Platform Functionalities
1
Getting into Software Design Patterns
Technical requirements
Code – from symbols to program
Examining OOP and APIE
Only exposing what’s required – encapsulation
Inevitable evolution – inheritance
Behavior on demand – polymorphism
Standard features – abstraction
Gluing parts to APIE
Understanding the SOLID design principles
The single-responsibility principle (SRP) – the engine is just an engine
The open-closed principle (OCP)
The Liskov Substitution Principle (LSP) – substitutability of classes
The interface segregation principle (ISP)
The dependency inversion principle (DIP)
Significance of design patterns
Reviewing what challenges design patterns solve
Summary
Questions
Further reading
2
Discovering the Java Platform for Design Patterns
Technical requirements
Knocking on Java’s door
Exploring the model and functionality of the Java platform
The JDK
The JRE
The JVM
Reviewing GC and the Java memory model
The JMM
GC and automatic memory management
Examining the core Java APIs
Primitive data types and wrappers
Working with the String API
Introducing arrays
Discovering a collection framework
Math APIs
Functional programming and Java
Introducing lambdas and functional interfaces
Using functional interfaces in lambda expressions
Getting to grips with the Java Module System
A quick review of Java features from 11 to 17+
The local variable syntax for lambda parameters (Java SE 11, JEP-323)
Switch expressions (Java SE 14, JEP-361)
Text blocks (Java SE 15, JEP-378)
Pattern matching for instanceof (Java SE 16, JEP-394)
Records (Java SE 16, JEP-395)
Sealed classes (Java SE 17, JEP-409)
UTF-8 by default (Java SE 18, JEP-400)
Pattern matching for switch (Java SE 18, Second Preview, JEP-420)
Understanding Java concurrency
From a basic thread to executors
Executing tasks
Summary
Questions
Further reading
Part 2: Implementing Standard Design Patterns Using Java Programming
3
Working with Creational Design Patterns
Technical requirements
It all starts with a class that becomes an object
Creating objects based on input with the factory method pattern
Motivation
Finding it in the JDK
Sample code
Conclusion
Creating objects from different families using the abstract factory pattern
Motivation
Finding it in the JDK
Sample code
Conclusion
Instantiating complex objects with the builder pattern
Motivation
Finding it in the JDK
Sample code
Conclusion
Cloning objects with the prototype pattern
Motivation
Finding it in the JDK
Sample code
Conclusion
Ensuring only one instance with the singleton pattern
Motivation
Finding it in the JDK
Sample code
Conclusion
Improving performance with the object pool pattern
Motivation
Finding it in the JDK
Sample code
Conclusion
Initiating objects on demand with the lazy initialization pattern
Motivation
Finding it in the JDK
Sample code
Conclusion
Reducing class dependencies with the dependency injection pattern
Motivation
Finding it in the JDK
Sample code
Conclusion
Summary
Questions
Further reading
4
Applying Structural Design Patterns
Technical requirements
Incompatible object collaboration with the adapter pattern
Motivation
Finding it in the JDK
Sample code
Conclusion
Decoupling and developing objects independently with the bridge pattern
Motivation
Finding it in the JDK
Sample code
Conclusion
Treating objects the same way using the composite pattern
Motivation
Finding it in the JDK
Sample code
Conclusion
Extending object functionality by using the decorator pattern
Motivation
Finding it in the JDK
Sample code
Conclusion
Simplifying communication with the facade pattern
Motivation
Finding it in the JDK
Sample code
Conclusion
Using conditions to select desired objects with the filter pattern
Motivation
Finding it in the JDK
Sample code
Conclusion
Sharing objects across an application with the flyweight pattern
Motivation
Finding it in the JDK
Sample code
Conclusion
Handling requests with the front-controller pattern
Motivation
Finding it in the JDK
Sample code
Conclusion
Identifying instances using the marker pattern
Motivation
Finding it in the JDK
Sample code
Conclusion
Exploring the concept of modules with the module pattern
Motivation
Finding it in the JDK
Sample code
Conclusion
Providing a placeholder for an object using the proxy pattern
Motivation
Finding it in the JDK
Sample code
Conclusion
Discovering multiple inheritance in Java with the twin pattern
Motivation
Sample code
Conclusion
Summary
Questions
Further reading
5
Behavioral Design Patterns
Technical requirements
Limiting expensive initialization using the caching pattern
Motivation
Finding it in the JDK
Sample code
Conclusion
Handling events using the chain of responsibility pattern
Motivation
Finding it in the JDK
Sample code
Conclusion
Turning information into action with the command pattern
Motivation
Finding it in the JDK
Sample code
Conclusion
Giving meaning to the context using the interpreter pattern
Motivation
Finding it in the JDK
Sample code
Conclusion
Checking all the elements with the iterator pattern
Motivation
Finding it in the JDK
Sample code
Conclusion
Utilizing the mediator pattern for information exchange
Motivation
Finding it in the JDK
Sample code
Conclusion
Restoring the desired state with the memento pattern
Motivation
Finding it in the JDK
Sample code
Conclusion
Avoiding a null pointer exception state with the null object pattern
Motivation
Finding it in the JDK
Sample code
Conclusion
Keeping all interested parties informed using the observer pattern
Motivation
Finding it in the JDK
Sample code
Conclusion
Dealing with instance stages by using the pipeline pattern
Motivation
Finding it in the JDK
Sample code
Conclusion
Changing object behavior with the state pattern
Motivation
Finding it in the JDK
Sample code
Conclusion
Using the strategy pattern to change object behavior
Motivation
Finding it in the JDK
Sample code
Conclusion
Standardizing processes with the template pattern
Motivation
Finding it in the JDK
Sample code
Conclusion
Executing code based on the object type using the visitor pattern
Motivation
Finding it in the JDK
Sample code
Conclusion
Summary
Questions
Further reading
Part 3: Other Essential Patterns and Anti-Patterns
6
Concurrency Design Patterns
Technical requirements
Decoupling a method execution with an active object pattern
Motivation
Sample code
Conclusion
Non-blocking tasks using async method invocation pattern
Motivation
Sample code
Conclusion
Delay execution until the previous task is completed with the balking pattern
Motivation
Sample code
Conclusion
Providing a unique object instance with a double-checked locking pattern
Motivation
Sample code
Conclusion
Using purposeful thread blocking via a read-write lock pattern
Motivation
Sample code
Conclusion
Decoupling the execution logic with a producer-consumer pattern
Motivation
Sample code
Conclusion
Executing isolated tasks with the scheduler pattern
Motivation
Sample code
Conclusion
Effective thread utilization using a thread-pool pattern
Motivation
Sample code
Conclusion
Summary
Questions
Further reading
Answers
7
Understanding Common Anti-Patterns
Technical requirements
What anti-patterns are and how to identify them
Theoretical principles challenges
Collecting technical debt as a bottleneck
Inappropriately squeezing the capabilities of the Java platform
Selecting the right tool
Conclusion of the code smell anti-pattern
Examining typical software anti-patterns
Spaghetti code
Cut and paste programming
Blob
Lava flow
Functional decomposition
Boat anchor
Conclusion
Understanding software architecture anti-patterns
Golden hammer
Continuous obsolescence
Input kludge
Working in a minefield
Ambiguous viewpoint
Poltergeists
Dead end
Conclusion
Summary
Further reading
Assessments
Index
Other Books You May Enjoy
Preface
The Java language is a tool for communicating with a very rich platform that provides many features ready to serve for application development. This book explores the latest developments in improving language syntax with examples of the most useful design patterns. The book reveals the relationship between features, patterns, and platform efficiency through example implementations. The book explores how theoretical foundations help improve the maintainability, efficiency, and testability of source code. The content helps the reader solve different tasks and provides guidance on how to approach programming challenges using a variety of sustainable and transparent approaches.
Who this book is for
This book is dedicated to all hungry
engineers who want to improve their software design skills with new language enhancements and a closer look at the Java platform.
What this book covers
Chapter 1, Getting into Software Design Patterns, introduces us to the initial foundations of source code design structure and outlines the principles that should be followed to achieve maintainability and readability.
Chapter 2, Discovering the Java Platform for Design Patterns, discusses the Java platform, which is a very broad and powerful tool. This chapter exposes the features, functions, and design of the Java platform in more detail to continue building the foundation needed to understand the purpose and value of using a design patterns.
Chapter 3, Working with Creational Design Patterns, explores object instantiation, which is a key part of any application. This chapter describes how to approach this challenge while keeping the requirements in mind.
Chapter 4, Applying Structural Design Patterns, shows how to create source code that allows for clarity of relationships between required objects.
Chapter 5, Behavioral Design Patterns, explores how to create source code that allows objects to communicate and exchange information while maintaining a transparent form.
Chapter 6, Concurrency Design Patterns, discusses the Java platform and how it is a concurrent environment by nature. It shows how to harness its power for the designed application’s purposes.
Chapter 7, Understanding Common Anti-Patterns, deals with anti-patterns that can be found in any application development