Book Image

Hands-On Design Patterns with Delphi

By : Primož Gabrijelčič
Book Image

Hands-On Design Patterns with Delphi

By: Primož Gabrijelčič

Overview of this book

Design patterns have proven to be the go-to solution for many common programming scenarios. This book focuses on design patterns applied to the Delphi language. The book will provide you with insights into the language and its capabilities of a runtime library. You'll start by exploring a variety of design patterns and understanding them through real-world examples. This will entail a short explanation of the concept of design patterns and the original set of the 'Gang of Four' patterns, which will help you in structuring your designs efficiently. Next, you'll cover the most important 'anti-patterns' (essentially bad software development practices) to aid you in steering clear of problems during programming. You'll then learn about the eight most important patterns for each creational, structural, and behavioral type. After this, you'll be introduced to the concept of 'concurrency' patterns, which are design patterns specifically related to multithreading and parallel computation. These will enable you to develop and improve an interface between items and harmonize shared memories within threads. Toward the concluding chapters, you'll explore design patterns specific to program design and other categories of patterns that do not fall under the 'design' umbrella. By the end of this book, you'll be able to address common design problems encountered while developing applications and feel confident while building scalable projects.
Table of Contents (18 chapters)
Title Page
Copyright and Credits
About Packt
Contributors
Preface
Index

Preface

Design patterns - my friend and enemy!

I learned about design patterns in the formative phase of my life as a programmer. (Yes, that was long ago. I don't even remember, how long ago.) Since then, I've always been a great admirer of the concept. I like structured programming and I like algorithms and methodological approaches to coding, so this design patterns idea has always looked like a potentially very interesting topic to me.

Potentially; that's the word. Almost all of the books explaining design patterns were written with C++ (and later Java) programmers in mind. Well, I could swallow that. I know how to program in C, and I can read C++ and Java, so that was an obstacle that I could surmount with some work. A bigger problem were the UML diagrams explaining the patterns and code examples that had no connection to reality.

Problem one – UML diagrams. I don't do UML. I tried to learn it few times, but it doesn't speak to me, and for the sake of my sanity, I'm unable to remember what all those empty circles, full circles, and other line endings are supposed to mean. Each time I saw a UML diagram in a design patterns book, I lost my patience and walked away.

Finally, the time has come for some payback! This book contains no UML diagrams at all. What's more, this book contains only one diagram describing a state machine, but even this diagram uses no formal notation - it is just my ad hoc sketch. Take that, UML design pattern-lovers! (Not really. I have deep respect for people who fluently use UML.)

Rather than drawing all kinds of diagrams, here, I've tried to explain how each pattern works in simple words. I've also tried to find more-or-less appropriate and analogous examples from the real world. I can only hope you'll like my approach. If not, you can still read this book and use any website describing design patterns to look at pretty diagrams at the same time.

My second problem was with code examples. With some rare exceptions, design pattern books and websites all repeat examples that were cited in the original Gang of Four publication (more on that in Chapter 1, Introduction to patterns). Those examples are all terribly outdated and irrelevant to a Delphi programmer. Which one of you needs to know how to use the Decorator pattern to apply scroll bars to a text view? There are many other uses for this pattern in the modern world – see the Chapter 5, Adapter, Proxy, Decorator, and Facade and consider the Adapter, Proxy, Decorator, and Facade patterns as examples.

Because of my deeply rooted dislike of such examples, I tried to stay away from them as much as possible. There are still examples that draw shapes onscreen in this book – simply because some patterns were designed specifically with such problems in mind – but the big majority of examples try to be closer to the experience of an average Delphi programmer. I also added few standalone sections on Delphi-specific language enhancements that may not be known to a fresh Delphi programmer, or to a Pascal programmer that doesn't speak Delphi. Look for them in headings starting with Delphi idioms.

Did I succeed in writing a easier to understand and more practical design pattern book? Only you can tell. (And please, do tell! I'll be glad to receive any feedback – positive or negative.) I can only say that this book has helped me – now I finally understand what this "design pattern" stuff is all about.

Who this book is for

This book was written for all Delphi programmers. It doesn't matter whether you are a beginner or an expert this book is for you!

While a basic knowledge of Delphi programming language and IDE is definitely a boon, you can read this book even if you know nothing about Delphi. The Pascal language is simple to read and understand, and when we come to advanced topics, the book explains the Delphi syntax with clear and simple examples.

The only requirement this book has from the reader is that they like to explore and learn. This is not a when this happens, do that kind of book. It explores interesting topics and gives insights and sketches of solutions, but doesn't contain any recipes claiming that this is the only proper way to do X.

This book will teach you to think, not how to reuse code.

What this book covers

Chapter 1, Introduction to patterns, introduces the concept of patterns. We'll see why patterns are useful and how they should be used in programming. The book will explore the difference between design principles, patterns, and idioms. It will present a hierarchical overview of design patterns, talk a bit about anti-patterns, and finish with a description of some important design principles.

 

 

Chapter 2Singleton, Dependency Injection, Lazy Initialization, and Object Pool, covers four patterns from the creational group. The chapter will firstly look into the singleton pattern, which makes sure that a class has only one instance. Next in line, the dependency injection pattern makes program architecture more flexible and appropriate for unit testing. In the second half, the chapter explores two optimization patterns. The lazy initialization pattern saves time and resources, while the object pool pattern speeds up creation of objects.

Chapter 3Factory Method, Abstract Factory, Prototype, and Builder, examines four more creational patterns. The factory method pattern simplifies creation of dependent objects. The concept can be extended into the abstract factory pattern, which functions as a factory of factories. The prototype pattern is used to create copies of objects. Last in this group, the builder pattern separates instructions for creating an object from its representation.

Chapter 4Composite, Flyweight, Marker Interface, and Bridge, covers four patterns from the structural group. The composite pattern allows client code to treat simple and complex objects the same. The flyweight pattern can be used to minimize memory usage by introducing data sharing between objects. The marker interface allows us to unleash a new level of programming power by introducing metaprogramming. The bridge pattern helps us separate an abstract interface from its implementation.

Chapter 5Adapter, Proxy, Decorator, and Facade, explores four more structural patterns. The adapter pattern helps in adapting old code to new use cases. The proxy pattern wraps an objects and exposes an identical interface to facilitate caching, remoting, and access control, among other things. Thedecorator pattern specifies how the functionality of existing objects can be expanded, while the facade pattern shows us how to create a simplified view of a complex system.

Chapter 6Nullable Object, Template Method, Command, and State, covers four patterns from the behavioral group. The null object pattern can reduce the need for frequent if statements in the code. The template method pattern helps with creating adaptable algorithms. The command pattern shows how we can treat actions as objects. It is a basis for Delphi actions. The state pattern allows an object to change its behavior on demand and is useful when we are writing state machines.

Chapter 7Iterator, Visitor, Observer, and Memento, examines four more behavioral patterns. The iterator pattern allows us to effectively access data structures in a structure-independent way. This pattern is the basis of Delphi's for..in construct. The visitor pattern allows us to extend classes in accordance with the Open/Closed design principle. To write loosely coupled programs that react to changes in the business model, we can use the observer pattern. When we need to store the state of a complex object, the memento pattern comes to help.

Chapter 8Lock Patterns, is entirely dedicated to data protection in a multithreaded world, and covers five concurrency patterns. The lock pattern enables the code to share data between threads and is basis for other patterns from this chapter. The lock striping pattern specifies how we can optimize locking when accessing a granular structure, such as an array. The double-checked locking pattern optimizes creation of shared resources, while the optimistic locking pattern speeds up this process even more. The readers-writer lock is a special version of the locking mechanism designed for situations where a shared resource is mostly read from, and only rarely written to.

Chapter 9Thread Pool, Messaging, Future, and Pipeline, finishes the overview of design patterns by exploring four more concurrency patterns. As a specialized version of the object pool pattern, the thread pool pattern speeds up thread creation. The messaging pattern can be used to remove shared data access completely, and by doing so, can simplify and speed up the program. The future pattern specifies how we can integrate parallel execution of calculations into existing code. This chapter ends with a discussion of the pipeline pattern, which is a practical application of messaging designed to speed up tasks that are hard to parallelize with other approaches.

Chapter 10Designing Delphi Programs, steps away from the design patterns and talks about concepts that are important for Delphi programmers. In this chapter, you will learn about event-driven programming and how the Delphi's event system can be extended with multicast events. We will explore the actions mechanism, which serves as a nice example of the command pattern. After that, the chapter will spend some time looking into the LiveBindings mechanism, an implementation of the observer pattern. In the second half of this chapter, we'll see how we can use form inheritance to create forms in an object-oriented way, and how we can use frames to create forms by compositions. At the end, we'll look into data modules; that is, tools that can be used to implement the table module enterprise pattern.

Chapter 11Other Kinds of Patterns, wraps up the book by exploring patterns in three areas. The first part of the chapter deals with the exceptions and introduces exception patterns; that is, a set of recommendations that will help you write better code. After that, a short treatise of debugging patterns tries to bring some order to the messy world of code debugging. To end the book, a short exploration of functional programming is used to explain how this kind of programming paradigm can be used in Delphi.

To get the most out of this book

Although you can read this book in bed or on the beach, you will need a computer and Delphi to play with the code examples. The code was written in Delphi 10.2 Tokyo, but it should also work without a problem in the older versions. All the code was also tested with the newest version of Delphi (at the time of publishing) – Delphi 10.3 Rio.

This book does not refer to any functionality specific to the Enterprise edition of Delphi. You'll be able to test all the code with the Professional edition, or even with the Community edition.

Download the example code files

You can download the example code files for this book from your account at www.packt.com. If you purchased this book elsewhere, you can visit www.packt.com/support and register to have the files emailed directly to you.

You can download the code files by following these steps:

  1. Log in or register at www.packt.com.
  2. Select the SUPPORT tab.
  3. Click on Code Downloads & Errata.
  4. Enter the name of the book in the Search box and follow the onscreen instructions.

Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:

  • WinRAR/7-Zip for Windows
  • Zipeg/iZip/UnRarX for Mac
  • 7-Zip/PeaZip for Linux

The code bundle for the book is also hosted on GitHub at https://github.com/PacktPublishing/Hands-On-Design-Patterns-with-Delphi.  In case there's an update to the code, it will be updated on the existing GitHub repository.

We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!

Conventions used

There are a number of text conventions used throughout this book.

CodeInText: Indicates code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles. Here is an example: "The project resides in a folder named adapter in the Chapter05/ directory."

A block of code is set as follows:

type
  IProducer = interface ['{8E4001F9-11EC-4C9C-BAD9-97C9601699FF}']
    function NextData: TValue;
  end;

Bold: Indicates a new term, an important word, or words that you see onscreen. For example, words in menus or dialog boxes appear in the text like this. Here is an example: "Select System info from the Administration panel."

Note

Warnings or important notes appear like this.

Note

Tips and tricks appear like this.

Get in touch

Feedback from our readers is always welcome.

General feedback: If you have questions about any aspect of this book, mention the book title in the subject of your message and email us at [email protected].

Errata: Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you have found a mistake in this book, we would be grateful if you would report this to us. Please visit www.packt.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details.

Piracy: If you come across any illegal copies of our works in any form on the Internet, we would be grateful if you would provide us with the location address or website name. Please contact us at [email protected] with a link to the material.

If you are interested in becoming an author: If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, please visit authors.packtpub.com.

Reviews

Please leave a review. Once you have read and used this book, why not leave a review on the site that you purchased it from? Potential readers can then see and use your unbiased opinion to make purchase decisions, we at Packt can understand what you think about our products, and our authors can see your feedback on their book. Thank you!

For more information about Packt, please visit packt.com.