Another handy pattern to use for frontend applications is the singleton. The singleton ensures that only one instance of a given object exists in your program. Moreover, it provides a global point of access to the object.

Here's what it looks like in practice:

export class MySingleton{ 
    //The constructor is private so we  
    //can't do `let singleton:MySingleton = new MySingleton();` 
    private static instance:MySingleton = null; 
    private constructor(){ 
    public static getInstance():MySingleton{ 
        if(MySingleton.instance == null){ 
            MySingleton.instance = new MySingleton(); 
        return MySingleton.instance; 
    } } 
 let singleton:MySingleton = MySingleton.getInstance();

We have a class that has a private static instance:MySingleton attribute. Then, ...

Get Angular Design Patterns now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.