📄 Page
1
(This page has no text content)
📄 Page
2
Software Design Patterns Software Design Patterns are reusable solutions to software development difficul- ties. However, a Software Design Pattern is not code; rather, it is a guide or para- digm that helps software engineers to construct products that follow best practices. A Design Pattern is more of a template to tackle the topic at hand than a library or framework, which can be added and utilized right away. Object-oriented pro- gramming (OOP) is supported by Design Patterns, which are based on the ideas of objects (instances of a class; data with unique attributes) and classes (user-defined types of data). Design Patterns are blueprints for resolving typical software engineer- ing issues. They provide reproducible solutions to some of the most prevalent dif- ficulties you’ll encounter. That said, Design Patterns aren’t a complete solution, nor are they code, classes, or libraries that you may use in your project. They are a type of problem-solving solution. Each job will be approached in a slightly different way. Why Should You Learn Software Design Patterns? As a programmer, you can use Software Design Patterns to help you build more re- liable structures. Design Patterns give you the skills to create smart and interactive applications or software with simple and easy problem-solving methods; they also allow you to create the greatest user-friendly apps and change them easily to meet the latest requirements. Design Patterns are interesting to deal with since such knowledge enables flexible coding patterns and techniques of structure, reusable codes, loosely written codes, classes, patterns, and so on. This book contains: • A step-by-step approach to problem solving and skill development • A quick run-through of the basic concepts, in the form of a “Crash Course” • Advanced, hands-on core concepts, with a focus on real-world problems • Industry level coding paradigm with practice-oriented explanations • Special emphasis on writing clean and optimized code, with additional chapters focused on coding methodology
📄 Page
3
(This page has no text content)
📄 Page
4
Software Design Patterns The Ultimate Guide Sufyan bin Uzayr
📄 Page
5
First edition published 2023 by CRC Press 6000 Broken Sound Parkway NW, Suite 300, Boca Raton, FL 33487-2742 and by CRC Press 4 Park Square, Milton Park, Abingdon, Oxon, OX14 4RN CRC Press is an imprint of Taylor & Francis Group, LLC © 2023 Sufyan bin Uzayr Reasonable efforts have been made to publish reliable data and information, but the author and publisher cannot assume responsibility for the validity of all materials or the consequences of their use. The authors and publishers have attempted to trace the copyright holders of all material reproduced in this publication and apologize to copyright holders if permission to publish in this form has not been obtained. If any copyright material has not been acknowledged please write and let us know so we may rectify in any future reprint. Except as permitted under U.S. Copyright Law, no part of this book may be reprinted, reproduced, transmitted, or utilized in any form by any electronic, mechanical, or other means, now known or hereafter invented, including photocopying, microfilming, and recording, or in any information storage or retrieval system, without written permission from the publishers. For permission to photocopy or use material electronically from this work, access www.copyright.com or contact the Copyright Clearance Center, Inc. (CCC), 222 Rosewood Drive, Danvers, MA 01923, 978-750-8400. For works that are not available on CCC please contact mpkbookspermissions@tandf. co.uk Trademark Notice: Product or corporate names may be trademarks or registered trademarks and are used only for identification and explanation without intent to infringe. Library of Congress Cataloging-in-Publication Data Names: Bin Uzayr, Sufyan, author. Title: Software Design Patterns : the ultimate guide / Sufyan bin Uzayr. Description: First edition. | Boca Raton : CRC Press, 2023. | Includes bibliographical references and index. Identifiers: LCCN 2022025677 (print) | LCCN 2022025678 (ebook) | ISBN 9781032311777 (hbk) | ISBN 9781032311760 (pbk) | ISBN 9781003308461 (ebk) Subjects: LCSH: Software patterns. Classification: LCC QA76.76.P37 B56 2023 (print) | LCC QA76.76.P37 (ebook) | DDC 005.13/267--dc23/eng/20220804 LC record available at https://lccn.loc.gov/2022025677 LC ebook record available at https://lccn.loc.gov/2022025678 ISBN: 9781032311777 (hbk) ISBN: 9781032311760 (pbk) ISBN: 9781003308461 (ebk) DOI: 10.1201/9781003308461 Typeset in Minion by KnowledgeWorks Global Ltd.
📄 Page
6
v Contents Acknowledgments, xv About the Author, xvii Chapter 1 ◾ Crash Course in Software Design Patterns 1 WHAT IS THE PURPOSE OF DESIGN PATTERNS? 2 WHY SHOULD WE STUDY DESIGN PATTERNS? 4 DESIGN PATTERN CONFIGURATION 4 Design Pattern 4 WHAT IS THE SIGNIFICANCE OF THE DESIGN PATTERN? 5 TYPES OF DESIGN PATTERNS 5 Creational 5 Use Case of Creational Design Patterns 5 Structural 6 Use Case of Structural Design Patterns 6 Behavioral 6 Use Case of Behavioral Design Patterns 7 WHAT EXACTLY IS THE GANG OF FOUR (GOF)? 7 USAGE OF DESIGN PATTERNS 7 Developers’ Common Platform 7 Guidelines for Best Practices 7 IMPORTANCE OF LEARNING DESIGN PATTERNS 8 TYPES OF DESIGN PATTERNS 8 DESIGN PATTERNS AND THEIR APPLICATIONS 9 PATTERNS OF CREATIONAL DESIGN 9
📄 Page
7
vi ◾ Contents PATTERNS OF STRUCTURAL DESIGN 10 PATTERNS OF BEHAVIORAL DESIGN 11 CRITICISM 12 Focusing on the Incorrect Issue 12 No Official Foundations 12 May Result in Inefficient Solutions 13 It is Not Notably Different from Other Abstractions 13 WHAT IS THE PURPOSE OF USING DESIGN PATTERNS? 13 DESIGN PATTERNS’ ADVANTAGES IN SOFTWARE ENGINEERING 14 SOFTWARE DESIGN PATTERN CRITIQUES 14 BEST SOFTWARE DESIGN PATTERNS 14 PATTERNS OF POPULAR SOFTWARE ARCHITECTURE 16 LIMITATIONS OF DESIGN PATTERNS 18 PROS OF DESIGN PATTERNS 18 DESIGN PATTERN CLASSIFICATION 19 Creational Design Patterns 19 Classification of Creational Design Patterns 19 Structural Design Patterns 20 Classification of Structural Design Patterns 20 Behavioral Design Patterns 20 Classification of Behavioral Design Patterns 20 Creational Design Patterns 21 Structural Design Patterns 21 Behavioral Design Patterns 21 DESIGN PATTERNS IN JAVA 21 Design Patterns in Software Development 21 Object Orientated Programming 22 Encapsulation 22 Abstraction 22 Polymorphisms 23 Inheritance 23
📄 Page
8
Contents ◾ vii Delegation 23 Composition 23 Aggregation 23 Contract Design 24 Cohesion 24 Principle of Least Knowledge 24 The Open-Closed Principle 24 Composition vs. Inheritance in Object-Oriented Design Patterns 25 Inheritance 25 Composition 26 Favoring Composition over Inheritance in Java (with Examples) 27 Inheritance 28 Composition 29 Composition over Inheritance 30 IS INHERITANCE EXTINCT? A CLOSER LOOK AT THE DECORATOR PATTERN 30 Exploding Class Hierarchy 31 To the Rescue Comes the Decorator Pattern 33 Decorators Queue 34 Testability 35 Other Advantages 35 Drawbacks 36 Decorator Pattern Has Native Support 37 Abstract Decorator 38 When Should We Use Inheritance? 39 KEY POINTS 40 Chapter 2 ◾ Factory Pattern 41 FACTORY METHOD 41 UML FOR FACTORY METHOD 42 PATTERNS FOR FACTORY PATTERN DESIGN 42 Problem 42 Solution 44
📄 Page
9
viii ◾ Contents ADVANTAGES OF USING THE FACTORY PATTERN 46 DRAWBACKS OF USING THE FACTORY PATTERN METHOD 46 APPLICABILITY 46 USES OF THE FACTORY DESIGN PATTERN 46 WHEN SHOULD WE UTILIZE FACTORY PATTERN METHODS? 47 Complex Logical Code Is Being Replaced 47 Bringing Together Related Functions under a Single Interface 47 Multiple Implementations of the Same Functionality Are Supported 47 Integrating External Series That Are Linked 47 PROBLEMS WE CONFRONT IN THE ABSENCE OF THE FACTORY METHOD 47 DISCUSSION 48 GENERAL GUIDELINES 48 Examples of Real-World Applications of the Factory Pattern Method Design in Java 49 Calculate An Electricity Bill: A Real-World Application of the Factory Method in Java 49 A Real-World Example of the Factory Design Pattern in C# 51 Chapter 3 ◾ Observer Pattern 59 PARTICIPANTS IN DESIGN 60 A PROBLEM 60 SOLUTION BASED ON THE OBSERVER PATTERN 60 CLASS DIAGRAM 63 ADVANTAGES 64 DISADVANTAGES 64 APPLICABILITY 64 USAGE 64 OBSERVER PATTERN’S PURPOSE 65 INTENT 65 PROBLEM 65 DISCUSSION 65
📄 Page
10
Contents ◾ ix EXAMPLE 66 CHECKLIST 66 RULES OF THUMB 66 Here’s a Real-World Example of an Observer Pattern in Java 67 IMPLEMENT THE OBSERVER PATTERN 67 Another Example 69 IObservable and IObserver (C#) Observer 71 USAGE 73 Chapter 4 ◾ Template Method Pattern 75 THE FACTORY METHOD VS. THE TEMPLATE METHOD 76 THE ABC LIBRARY 77 WHEN SHOULD THE TEMPLATE METHOD PATTERN BE USED? 77 USING PYTHON TO IMPLEMENT THE TEMPLATE METHOD DESIGN PATTERN 78 ADVANTAGES 81 DISADVANTAGES 82 APPLICABILITY 82 USAGE 82 IMPORTANT POINTS 82 TEMPLATE METHOD PATTERN IMPLEMENTATION IN JAVA 83 TEMPLATE METHOD IN C# 87 Participants 87 C# Structural Code 87 Real-World C# Code 88 Chapter 5 ◾ Singleton Pattern 93 MOTIVATION 94 REAL-WORLD EXAMPLE 94 IMPLEMENTATION 95 Method 1: Design Pattern of Monostate/Borg Singleton 95
📄 Page
11
x ◾ Contents CLASSIC IMPLEMENTATION OF SINGLETON DESIGN PATTERN 97 CLASS DIAGRAM 98 BENEFITS OF USING THE SINGLETON PATTERN 99 DISADVANTAGES OF EMPLOYING THE SINGLETON PATTERN 99 APPLICABILITY 99 USAGE OF SINGLETON DESIGN PATTERN 99 How to Implement the Singleton Design Pattern in Java 100 UNDERSTANDING EARLY SINGLETON PATTERN INSTANTIATION 100 UNDERSTANDING THE LAZY SINGLETON INSTANTIATION PATTERN 100 IMPORTANCE OF SERIALIZATION IN THE SINGLETON PATTERN 101 UNDERSTANDING A REAL-WORLD EXAMPLE OF THE SINGLETON PATTERN 102 ASSUMPTION 102 C# Singleton Pattern 108 Participants 108 C# Structural Code 108 Real-World C# Code 110 Chapter 6 ◾ Strategy Pattern 113 INTRODUCTION 113 STRATEGY 114 USAGE 114 UML DIAGRAMS 115 IMPLEMENTATION 116 EXAMPLE 118 BENEFITS 119 DOWNSIDES 120 APPLICABILITY 120 Example of a Real-Time Strategy Pattern – Payment in Java 120
📄 Page
12
Contents ◾ xi STRATEGY PATTERN IMPLEMENTATION IN JAVA 120 C# Strategy Pattern 123 Participants 123 C# Structural Code 123 Real-World C# Code 125 Chapter 7 ◾ Proxy Pattern 129 WHY WOULD WE USE IT? 131 BETTER TESTABILITY 133 INTERFACE USING PROXY PATTERN 133 ANOTHER USEFUL EXAMPLE 135 HOW SHOULD THE PROXY PATTERN BE IMPLEMENTED? 139 ADVANTAGES 140 DISADVANTAGES 140 APPLICABILITY 141 IMPLEMENTATION 142 C# Proxy Pattern 143 Participants 143 C# Structural Code 144 Real-World C# Code 146 Chapter 8 ◾ Bridge Pattern 149 BRIDGE DESIGN PATTERN ELEMENTS 149 THE INSPIRATION FOR THE BRIDGE DESIGN PATTERN 150 USING PYTHON TO IMPLEMENT THE BRIDGE DESIGN PATTERN 151 A PROBLEM 154 SOLUTION USING BRIDGE PATTERN 156 UML DIAGRAM OF BRIDGE PATTERN 158 REAL-WORLD BRIDGE DESIGN PATTERN 158 ADVANTAGES 158 DISADVANTAGES 159 APPLICABILITY 159
📄 Page
13
xii ◾ Contents USAGE OF BRIDGE PATTERN 159 Using the Bridge Pattern in Java 160 Bridge Pattern in C# 163 Participants 163 C# Structural Code 163 Real-World C# Code 165 Chapter 9 ◾ Adapter and Façade Patterns 171 ADAPTER PATTERN 171 USING THE ADAPTER PATTERN TO SOLVE A PROBLEM 172 ADAPTER PATTERN SOLUTIONS 173 CLASS DIAGRAM 175 ADVANTAGES 175 DISADVANTAGES 175 APPLICABILITY 176 ADAPTER PATTERN USAGE 176 An Example of the Adapter Pattern in Java 176 Adapter Pattern in C# 178 Participants 178 C# Structural Code 179 Real-World C# Code 180 FACADE PATTERN 183 A PROBLEM 184 SOLUTION BASED ON THE FACADE PATTERN 185 CLASS DIAGRAM FOR THE FACADE METHOD 186 ADVANTAGES 186 DISADVANTAGES 186 APPLICABILITY 187 FACADE PATTERN USAGE 187 Implementation in Java 187
📄 Page
14
Contents ◾ xiii Facade Pattern in C# 190 Participants 190 C# Structural Code 190 Real-World C# Code 193 APPRAISAL, 197 BIBLIOGRAPHY, 419 INDEX, 429
📄 Page
15
(This page has no text content)
📄 Page
16
xv Acknowledgments There are many people who deserve to be on this page, for this book would not have come into existence without their support. That said, some names deserve a special mention, and I am genuinely grateful to: • My parents, for everything they have done for me. • My siblings, for helping with things back home. • The Parakozm team, especially Divya Sachdeva, Jaskiran Kaur, and Vartika, for offering great amounts of help and assistance during the book-writing process. • The CRC team, especially Sean Connelly and Danielle Zarfati, for ensuring that the book’s content, layout, formatting, and everything else remain perfect throughout. • Reviewers of this book, for going through the manuscript and pro- viding their insight and feedback. • Typesetters, cover designers, printers, and all related roles, for their part in the development of this book. • All the folks associated with Zeba Academy, either directly or indi- rectly, for their help and support. • The programming community in general, and the web development community in particular, for all their hard work and efforts. Sufyan bin Uzayr
📄 Page
17
(This page has no text content)
📄 Page
18
xvii About the Author Sufyan bin Uzayr is a writer, coder, and entrepreneur with over a decade of experience in the industry. He has authored several books in the past, per- taining to a diverse range of topics, ranging from History to Computers/IT. Sufyan is the Director of Parakozm, a multinational IT company spe- cializing in EdTech solutions. He also runs Zeba Academy, an online learning and teaching vertical with a focus on STEM fields. Sufyan specializes in a wide variety of technologies, such as JavaScript, Dart, WordPress, Drupal, Linux, and Python. He holds multiple degrees, including ones in Management, IT, Literature, and Political Science. Sufyan is a digital nomad, dividing his time between four countries. He has lived and taught in universities and educational institutions around the globe. Sufyan takes a keen interest in technology, politics, literature, history, and sports, and in his spare time, he enjoys teaching coding and English to young students. Learn more at sufyanism.com.
📄 Page
19
(This page has no text content)
📄 Page
20
1DOI: 10.1201/9781003308461-1 C h a p t e r 1 Crash Course in Software Design Patterns IN THIS CHAPTER ➢ What are Software Design Patterns? ➢ Major concepts ➢ Advantages and disadvantages ➢ Additional info Design Patterns represent some of the most acceptable practices experi- enced object-oriented software engineers utilize. In object-oriented sys- tems, a Design Pattern methodically names, motivates, and describes a general design that addresses a recurring design challenge. It explains the problem, the remedy, when to use it, and the repercussions. It also includes tips and examples for implementation. A Design Pattern is a broad, reusable solution to common software design challenges. Typically, the pattern depicts relationships and inter- actions between classes or objects. The goal is to accelerate the develop- ment process by providing tried-and-true development/design paradigms. Design Patterns are strategies for solving a common problem independent of programming language. A Design Pattern represents an idea rather than