Book Image

TypeScript Design Patterns

By : Vilic Vane
Book Image

TypeScript Design Patterns

By: Vilic Vane

Overview of this book

In programming, there are several problems that occur frequently. To solve these problems, there are various repeatable solutions that are known as design patterns. Design patterns are a great way to improve the efficiency of your programs and improve your productivity. This book is a collection of the most important patterns you need to improve your applications’ performance and your productivity. The journey starts by explaining the current challenges when designing and developing an application and how you can solve these challenges by applying the correct design pattern and best practices. Each pattern is accompanied with rich examples that demonstrate the power of patterns for a range of tasks, from building an application to code testing. We’ll introduce low-level programming concepts to help you write TypeScript code, as well as work with software architecture, best practices, and design aspects.
Table of Contents (15 chapters)
TypeScript Design Patterns
Credits
About the Author
About the Reviewer
www.PacktPub.com
Preface

Singleton


There are scenarios in which only one instance of the specific class should ever exist, and that leads to Singleton Pattern.

Basic implementations

The simplest singleton in JavaScript is an object literal; it provides a quick and cheap way to create a unique object:

const singleton = { 
  foo(): void { 
    console.log('bar'); 
  } 
}; 

But sometimes we might want private variables:

const singleton = (() => { 
  let bar = 'bar'; 
   
  return { 
    foo(): void { 
      console.log(bar); 
    } 
  }; 
})(); 

Or we want to take the advantage of an anonymous constructor function or class expression in ES6:

const singleton = new class { 
  private _bar = 'bar'; 
   
  foo(): void { 
    console.log(this._bar); 
  } 
} (); 

Note

Remember that the private modifier only has an effect at compile time, and simply disappears after being compiled to JavaScript (although of course its accessibility...