Table Of ContentDesign Patterns and Best
Practices in Java
A comprehensive guide to building smart and reusable code
in Java
Kamalmeet Singh
Adrian Ianculescu
Lucian-Paul Torje
BIRMINGHAM - MUMBAI
Design Patterns and Best Practices in Java
Copyright © 2018 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
authors, 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.
Commissioning Editor: Kunal Parikh
Acquisition Editor: Alok Dhuri
Content Development Editor: Nikhil Borkar
Technical Editor: Jash Bavishi
Copy Editor: Safis Editing
Project Coordinator: Ulhas Kambali
Proofreader: Safis Editing
Indexer: Rekha Nair
Graphics: Tania Dutta
Production Coordinator: Arvindkumar Gupta
First published: June 2018
Production reference: 1250618
Published by Packt Publishing Ltd.
Livery Place
35 Livery Street
Birmingham
B3 2PB, UK.
ISBN 978-1-78646-359-3
www.packtpub.com
mapt.io
Mapt is an online digital library that gives you full access to over 5,000 books and videos, as
well as industry leading tools to help you plan your personal development and advance
your career. For more information, please visit our website.
Why subscribe?
Spend less time learning and more time coding with practical eBooks and Videos
from over 4,000 industry professionals
Improve your learning with Skill Plans built especially for you
Get a free eBook or video every month
Mapt is fully searchable
Copy and paste, print, and bookmark content
PacktPub.com
Did you know that Packt offers eBook versions of every book published, with PDF and
ePub files available? You can upgrade to the eBook version at www.PacktPub.com and as a
print book customer, you are entitled to a discount on the eBook copy. Get in touch with us
at service@packtpub.com for more details.
At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a
range of free newsletters, and receive exclusive discounts and offers on Packt books and
eBooks.
About the authors
Kamalmeet Singh got his first taste of programming at the age of 15, and he immediately
fell in love with it. After getting his bachelor’s degree in information technology, he joined a
start-up, and his love for Java programming grew further. After spending over 13 years in
the IT industry and working in different companies, countries, and domains, Kamal has
matured into an ace developer and a technical architect. The technologies he works with
include cloud computing, machine learning, augmented reality, serverless applications,
microservices, and more, but his first love is still Java.
I would like to thank my wife, Gundeep, who always encourages me to take up new
challenges and brings out the best in me.
Adrian Ianculescu is a software developer with 20 years of programming experience, of
which 12 years were in Java, starting with C++, then working with C#, and moving
naturally to Java. Working in teams ranging from 2 to 40, he realized that making software
is not only about writing code, and became interested in software design and architecture,
in different methodologies and frameworks. After living the corporate life for a while, he
started to work as a freelancer and entrepreneur, following his childhood passion to make
games.
Lucian-Paul Torje is an aspiring software craftsman who has been working in the software
industry for almost 15 years. He is interested in almost anything that has to do with
technology. This is why he has worked with everything from MS-DOS TSR to
microservices, from Atmel microcontrollers to Android, iOS, and Chromebooks, from
C/C++ to Java, and from Oracle to MongoDB. Whenever someone is needed to use new and
innovative approaches to solve a problem, he is keen to give it a go!
About the reviewer
Aristides Villarreal Bravo is a Java developer, a member of the NetBeans Dream
Team, and a Java User Groups leader. He lives in Panama. He has organized and
participated in various conferences and seminars related to Java, JavaEE, NetBeans, the
NetBeans platform, free software, and mobile devices. He is the author of jmoordb and
tutorials and blogs about Java, NetBeans, and web development.
Aristides has participated in several interviews on sites about topics such as
NetBeans, NetBeans DZone, and JavaHispano. He is a developer of plugins for NetBeans.
My mother, father, and all family and friends.
Packt is searching for authors like you
If you're interested in becoming an author for Packt, please visit authors.packtpub.com
and apply today. We have worked with thousands of developers and tech professionals,
just like you, to help them share their insight with the global tech community. You can
make a general application, apply for a specific hot topic that we are recruiting an author
for, or submit your own idea.
Table of Contents
Preface 1
Chapter 1: From Object-Oriented to Functional Programming 5
Java – an introduction 5
Java programming paradigms 6
Imperative programming 6
Real-life imperative example 6
Object-oriented paradigm 7
Objects and classes 7
Encapsulation 7
Abstraction 8
Inheritance 8
Polymorphism 9
Declarative programming 10
Functional programming 11
Working with collections versus working with streams 11
An introduction to Unified Modeling Language 12
Class relations 14
Generalization 15
Realization 15
Dependency 16
Association 16
Aggregation 16
Composition 17
Design patterns and principles 17
Single responsibility principle 18
Open/closed principle 20
Liskov Substitution Principle 20
Interface Segregation Principle 22
Dependency inversion principle 23
Summary 24
Chapter 2: Creational Patterns 26
Singleton pattern 26
Synchronized singletons 28
Synchronized singleton with double-checked locking mechanism 29
Lock-free thread-safe singleton 29
Early and lazy loading 30
The factory pattern 30
Simple factory pattern 31
Table of Contents
Static factory 32
Simple factory with class registration using reflection 33
Simple factory with class registration using Product.newInstance 34
Factory method pattern 35
Anonymous concrete factory 37
Abstract factory 37
Simple factory versus factory method versus abstract factory 39
Builder pattern 39
Car builder example 40
Simplified builder pattern 42
Anonymous builders with method chaining 43
Prototype pattern 44
Shallow clone versus deep clone 45
Object pool pattern 45
Summary 47
Chapter 3: Behavioral Patterns 48
The chain-of-responsibility pattern 48
Intent 49
Implementation 49
Applicability and examples 51
The command pattern 52
Intent 52
Implementation 52
Applicability and examples 54
The interpreter pattern 55
Intent 55
Implementation 56
Applicability and examples 59
The iterator pattern 60
Intent 60
Implementation 60
Applicability and examples 62
The observer pattern 63
Intent 63
Implementation 63
The mediator pattern 64
Intent 65
Implementation 65
Applicability and examples 65
The memento pattern 66
Intent 66
Implementation 66
Applicability 68
The state pattern 69
[ ii ]
Table of Contents
The strategy pattern 69
Intent 69
Implementation 70
The template method pattern 70
Intent 71
Implementation 71
The null object pattern 71
Implementation 72
The visitor pattern 72
Intent 73
Implementation 73
Summary 74
Chapter 4: Structural Patterns 75
Adapter pattern 76
Intent 76
Implementation 77
Examples 77
Proxy pattern 82
Intent 83
Implementation 83
Examples 84
Decorator pattern 86
Intent 87
Implementation 87
Examples 88
Bridge pattern 89
Intent 90
Implementation 90
Examples 91
Composite pattern 93
Intent 93
Implementation 94
Examples 95
Façade pattern 97
Intent 97
Implementation 98
Examples 99
Flyweight pattern 101
Intent 102
Implementation 102
Examples 103
Summary 107
Chapter 5: Functional Patterns 108
[ iii ]
Table of Contents
Introducing functional programming 108
Lambda expressions 110
Pure functions 111
Referential transparency 111
First-class functions 111
Higher-order functions 112
Composition 112
Currying 113
Closure 113
Immutability 114
Functors 114
Applicatives 115
Monads 116
Introducing functional programming in Java 116
Lambda expressions 117
Streams 118
Stream creator operations 119
Stream intermediate operations 119
Stream terminal operations 122
Re-implementing OOP design patterns 122
Singleton 122
Builder 123
Adapter 124
Decorator 124
Chain of responsibility 125
Command 125
Interpreter 125
Iterator 126
Observer 126
Strategy 127
Template method 127
Functional design patterns 128
MapReduce 128
Intent 128
Examples 128
Loan pattern 129
Intent 129
Examples 130
Tail call optimization 130
Intent 130
Examples 131
Memoization 131
Intent 131
Examples 132
The execute around method 133
Intent 133
[ iv ]