Search icon
Arrow left icon
All Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletters
Free Learning
Arrow right icon
TypeScript 4 Design Patterns and Best Practices

You're reading from  TypeScript 4 Design Patterns and Best Practices

Product type Book
Published in Sep 2021
Publisher Packt
ISBN-13 9781800563421
Pages 350 pages
Edition 1st Edition
Author (1):
 Theofanis Despoudis Theofanis Despoudis
Profile icon Theofanis Despoudis

Table of Contents (14) Chapters

Preface 1. Section 1: Getting Started with TypeScript 4
2. Chapter 1: Getting Started with Typescript 4 3. Chapter 2: TypeScript Core Principles 4. Section 2: Core Design Patterns and Concepts
5. Chapter 3: Creational Design Patterns 6. Chapter 4: Structural Design Patterns 7. Chapter 5: Behavioral Design Patterns 8. Section 3: Advanced Concepts and Best Practices
9. Chapter 6: Functional Programming with TypeScript 10. Chapter 7: Reactive Programming with TypeScript 11. Chapter 8: Developing Modern and Robust TypeScript Applications 12. Chapter 9: Anti-Patterns and Workarounds 13. Other Books You May Enjoy

Chapter 3: Creational Design Patterns

When developing applications, you design and manage objects all the time. You create them on the fly or when you assign them to variables for later use. If left unnoticed, you can make the code brittle either by having lots and lots of alternative ways to create those objects, or by not managing their lifetime correctly, thus having to deal with memory leaks.

The first and most used category of patterns we will explore in detail in this chapter is creational design patterns.

You start by learning how the Singleton pattern can help to ensure we merely keep one instance of an object throughout the lifetime of the program. By using the Prototype pattern, you can copy existing objects without going back through the process of creating them from scratch.

Using the Builder pattern, you will learn how to break apart the construction flow of complex objects by using a different and more readable representation.

Next, you continue comprehending...

Creational design patterns

When you declare interfaces and classes in TypeScript, the compiler takes that information and uses it when performing type checks or other assertions. Then at runtime, when the browser or the server evaluates the code, it creates and manages those objects for the duration of the application life cycle. Sometimes you can create objects at the start of the application, for example, you saw the object creation of the Express.js app in the previous chapter:

const app = express(); 

Other times, you might create objects on the fly using an object descriptor. For example, you saw in Chapter 2, TypeScript Core Principles, how you can create HTML span elements:

const span = document.createElement("span");

Both of these approaches deal with object creation, and more specifically, how to instantiate a type of object and store it somewhere. If you think about that for a minute, then you will realize there are two distinct phases here:

  • Creating...

Singleton pattern

The first and the most simple design pattern that you will find almost everywhere is the Singleton pattern. We will start by learning what a Singleton is and what problems it can solve. Then, you will study both the classic implementation and some modern alternatives. Finally, we list some of the major disadvantages of Singletons.

The term Singleton describes something that has only a single presence in the program. You use it when you want to get hold of a single object instead of many different ones for several reasons. For example, maybe you want to keep only one instance of a particular class simply because it is either expensive to create or it does not make sense to keep more than one for the lifetime of the program.

Note

When we mention a program, we refer to the current runtime environment, which in most cases consists of a single process that has access to all program memory. Due to the Operating System (OS) and other considerations, when you spawn...

Prototype pattern

The next creational design pattern that you will study is the Prototype. This pattern helps abstract the object creation process. Let's explore in detail what we mean.

A Prototype is a kind of object that takes its initial state and properties out of existing objects. The main idea is to avoid having to manually create an object and assign properties to it from another object.

Using a Prototype pattern, you can use objects that implement the Prototype interface. Instead of creating a new object by calling the new operator, you instead follow a divergent path. You construct objects that adhere to the Prototype interface, which has a single method, clone(). When called, it will clone the existing instance of the object and its internal properties. You can avoid duplicating the logic of creating a new object and assigning common functionality. You will now learn what the ideal circumstances are for using this pattern.

When do we use the Prototype pattern...

Builder pattern

The third design pattern that you will learn about now is the Builder pattern. This pattern deals with simplifying the process of creating complex objects. We start by learning more about Builder and why it exists. You will then see a typical implementation in TypeScript together with some modern variants. At the end of this section, you will get all the necessary skills to apply this pattern when needed in real-world applications.

Builder is a creational design pattern that you can use to deal with the step-by-step construction of objects that can have multiple future representations. Quite often you create objects that take more than two or three parameters and many of those parameters are not known ahead of time. They are required, though, to initialize the object with the right state.

We might have complex objects for a variety of reasons. For example, the business domain might want to attach several cohesive attributes to the objects for easier access. In...

Factory method pattern

The fourth design pattern that you will learn now is the Factory method. This pattern deals with the creation of objects and particularly with delegating the creation of objects using sub-classes. The objects you want to create usually share a common characteristic; they are similar in nature or in type, or they are part of a hierarchy.

You use an interface with a distinct create method and then you provide concrete classes that implement this factory and construct objects of a particular sub-class. Then this factory interface can be used in places where you have hardcoded types in parameters or variables.

A factory object is an abstraction that is responsible for creating objects. The way that it creates them though is the key differentiator. When you have multiple types of objects that either inherit from a similar class or have a similar role, then you may find that passing each type as a parameter is cumbersome. You will have to create all those different...

Abstract Factory pattern

The Abstract Factory is a creational design pattern that lets you create an abstract representation of factories without specifying concrete classes. You can think of this pattern as a factory of factories. You use it to create a common shape of factory objects and then when you want to use them in practice, you implement specific methods to create those objects.

Using this pattern, you retain the flexibility to define multiple concrete implementations for the factories without altering the process of using them. The client code is easier to change and manages a different factory at runtime. Let's describe the reasons to use this pattern in practice.

When do we use the Abstract Factory?

This pattern provides a way to encapsulate the basic building methods for creating families of related objects. Those are the key observations and criteria to understand before applying this pattern:

  • Need a factory of related objects: Instead of creating...

Summary

We started by discovering the details of the Singleton pattern and how it aids us in controlling unique instances of objects. Next, you examined how the Prototype pattern allows us to specify what kinds of objects we want to create, and clone them using those kinds as a base. Next, you learned how the Builder pattern allows us to construct complex objects. Lastly, you learned that by using the Factory and Abstract Factory patterns, you can separate the creation process of objects from their representation and are also able to describe factories of factories.

In the next chapter, you will continue learning more about structural design patterns, which are patterns that ease the process of design by identifying a simple way to realize relationships between entities.

Q&A

  1. How is Façade different compared to the Proxy pattern?

    Façade shares some common characteristics of the Proxy pattern. However, Façade does not need to have the same interface with the service objects or sub-system it tries to encapsulate.

  2. How is Decorator different compared to the Proxy pattern?

    Both patterns are fairly similar, but they have different functionalities and responsibilities. Decorator is used by the client, which cannot add or remove them at runtime. With Proxy, the client does not usually have this flexibility as it is usually hidden from the client.

Further reading

lock icon The rest of the chapter is locked
You have been reading a chapter from
TypeScript 4 Design Patterns and Best Practices
Published in: Sep 2021 Publisher: Packt ISBN-13: 9781800563421
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $15.99/month. Cancel anytime}