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

Double-checked locking

When we are writing code that sometimes requires some object to be created, and sometimes not, we can save some execution time by only creating this object when it is needed. This process-lazy initialization is explained in Chapter 2, Singleton, Dependency Injection, Lazy Initialization, and Object Pool. That chapter, however, only covered single-threaded applications.

To do lazy initialization properly in a multithreaded world, we need locking. And to do it correctly and fast, we need a double-checked locking pattern. This pattern can speed up any lock that is only acquired if some condition is met. It is also called test, lock, and test again.


For instance, when you are changing lanes in a car, you check the traffic around you first, then turn on your indicator, check the traffic again, and then change lane.

In the demonstration program DoubleCheckedLocking from the Double-checked locking folder, the TLazyOwner class functions as an owner that can create a field...