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

The command pattern


One of the most important things to do in object-oriented programming is to adopt a design that lets us decouple the code. For example, let's imagine that we need to develop a complex application in which we can draw graphic shapes: points, lines, segments, circles, rectangles, and many more.

Along with the code to draw all kinds of shapes, we need to implement many operations to handle the menu operations. In order to make our application maintainable, we are going to create a unified way to define all those commands in such a way that it will hide the implementation details from the rest of the application (which plays the client role).

Intent

The command pattern does the following:

  • Provides a unified way to encapsulate a command along with the required parameters to execute an action
  • Allows the handling of commands, such as storing them in queues

Implementation

The class diagram of the command pattern is as follows:

We can distinguish the following actors in the preceding...