Book Image

Design Patterns and Best Practices in Java

By : Kamalmeet Singh, Adrian Ianculescu, Lucian-Paul Torje
Book Image

Design Patterns and Best Practices in Java

By: Kamalmeet Singh, Adrian Ianculescu, Lucian-Paul Torje

Overview of this book

Having a knowledge of design patterns enables you, as a developer, to improve your code base, promote code reuse, and make the architecture more robust. As languages evolve, new features take time to fully understand before they are adopted en masse. The mission of this book is to ease the adoption of the latest trends and provide good practices for programmers. We focus on showing you the practical aspects of smarter coding in Java. We'll start off by going over object-oriented (OOP) and functional programming (FP) paradigms, moving on to describe the most frequently used design patterns in their classical format and explain how Java’s functional programming features are changing them. You will learn to enhance implementations by mixing OOP and FP, and finally get to know about the reactive programming model, where FP and OOP are used in conjunction with a view to writing better code. Gradually, the book will show you the latest trends in architecture, moving from MVC to microservices and serverless architecture. We will finish off by highlighting the new Java features and best practices. By the end of the book, you will be able to efficiently address common problems faced while developing applications and be comfortable working on scalable and maintainable projects of any size.
Table of Contents (15 chapters)
Title Page
Packt Upsell
Contributors
Preface
Index

Adapter pattern


The adapter pattern provides a solution for code reusability; it adapts/wraps existing old code to new interfaces, interfaces that were unknown at the design time of the original code. In 1987, when the PS/2 port was designed, no one imagined that it would be connected to a USB bus designed nine years later. Yet we can still use an old PS/2 keyboard in our newest computer by connecting it to the USB port.

The adapter pattern is commonly used when working with legacy code, since by wrapping the existing code and adapting it to the new code interface, we instantly gain access to the old, already-tested, functionality. This can be done either by using multiple inheritances, made possible in Java 8 by default interface implementation, or by using composition, where the old object becomes a class attribute. The adapter pattern is also known as a wrapper.

In cases where the old code needs to make use of the new code, and vice-versa, we need to use a special adapter called a two-way...