DEV Community

loading...
Cover image for Master Design Patterns By Building Real Projects - Singleton Pattern - Javascript

Master Design Patterns By Building Real Projects - Singleton Pattern - Javascript

hieptl profile image Hiep Le Updated on ・3 min read

Creational Pattern - Singleton Pattern.

This is the first part in my series (23 GoF Design Patterns). My series will help you understand about design patterns by building real projects. For this reason, you can see the place in which each pattern could be applied. I want to focus on learning by doing instead of talking too much about theories.

I'm Hiep. I work as a full-time software engineer. Most of my open-source projects are focused on one thing - to help people learn 📚.

I created a git repository that help you understand about design patterns by building real projects.

Github link:

https://github.com/hieptl/javascript-dessign-patterns

If The repository is useful, please help me share the post and give me a Github's star. It will make me feel motivation to work even harder. I will try to make many open sources and share to the community ❤️.

I also created some series that help you improve your practical skills ❤️

1. Learn React By Building Netflix

https://dev.to/hieptl/learn-react-by-building-netflix-1127

Table of Contents

1. Definition.

Singleton pattern will be used to ensure a class has only one instance, and provide a global point of access to it.

2. Scenarios.

We want to display something on the console, we often use console.log statement.

However, the information should be displayed in different formats (table format or including date and time, etc). Hence, we should create Logger class that include different methods in order to achieve that and we can use it in different places in our applications.

Whenever we need to use Logger class, we have to create a new instance of Logger class by writing something like this:

const logger = new Logger();

In this case, creating different logger instances is not neccessary. Therefore, we should find a way to create a single instance which could be reused instead of creating the new one.

3. Building Logger.

Our Logger class will be looked like this:

class Logger {
  constructor() {
    if (Logger._instance) {
      console.log('return previously created logger object instead of creating a new one');
      return Logger._instance;
    }
    console.log('create new logger object for the first time');
    Logger._instance = this;
    return this;
  }

  log (...logs) {
    logs.forEach(log => console.log(log));
  }

  logWithTableFormat(...logs) {
    console.table(logs);
  }
}

const firstLogger = new Logger();
const secondLogger = new Logger();

console.log(`are firstLogger and secondLogger the same ? ${firstLogger === secondLogger}`);

firstLogger.log({userName: 'hieptl', job: 'Software Engineer'});
secondLogger.logWithTableFormat({userName: 'hieptl', job: 'Software Engineer'});
Enter fullscreen mode Exit fullscreen mode

In the constructor, we will check if the instance was created, that instance would be returned instead of creating the new one.

If the instance was not created, we would create a new instance and assign to Logger._instace so that we can reuse that instance later.

4. Result.

create new logger object for the first time
return previously created logger object instead of creating a new one
are firstLogger and secondLogger the same ? true
{ userName: 'hieptl', job: 'Software Engineer' }
┌─────────┬──────────┬─────────────────────┐
 (index)  userName          job         
├─────────┼──────────┼─────────────────────┤
    0     'hieptl'  'Software Engineer' 
└─────────┴──────────┴─────────────────────┘
Enter fullscreen mode Exit fullscreen mode

The above result describes about the first logger instance and the second logger instance are the same.
On the other hand, our Logger class can display the information in different formats.

I hope that the post can help you understand about singleton pattern.

Thanks and Best Regards,
Hiep.

Discussion (6)

Collapse
adam_cyclones profile image
Adam Crockett

This is a great series idea good job. This pattern is my least favourite in languages like JavaScript, doesn't make sense to me, write a class that isn't going to be instanced, that's an object literal with functions in my book. I have a book now 😂, anyway good job

Collapse
hieptl profile image
Hiep Le Author • Edited

Hi @adam_cyclones , I really appreciate your opinion and you are the first person who commented on my post. Thank you so much ❤️. From my point of view, object-oriented programming, design patterns, data structures and algorithms, principles are really important for developers. In fact, programming languages could be changed in the future. I totally agree with you that we can have several ways to achieve the same result by using Javascript. I used Javascript class in my example for some of reasons. If the developers have to change from Javascript to other programming languages such as Java, C#, ... They have to work with classes, they will not feel surprise. That's why I used Javascript class in my example 😄 In my opinion, design patterns are mindset and approaches not tools or languages.
Thanks and Best Regards,
Hiep.

Collapse
venom94 profile image
venom

You're made my day, keep doing, thanks :))

Collapse
hieptl profile image
Hiep Le Author

Hi @venom94 , Thank you so much ❤️ I am writing the next parts for this series. On the other hand, I am writing about different topics such as React, Javascript and so on. If you feel my repositories and articles are useful, please help me share them to the community ⭐

Collapse
ingjorgevasquez profile image
Jorge Vasquez

I love the simplicity you have when explaining this concept. Thank you for taking the time to write about design patterns

Collapse
hieptl profile image
Hiep Le Author

Hi @ingjorgevasquez , Thank you so much ❤️ I am writing the next parts for this series. If you like the series, please help me share the series to the community. On the other hand, I am writing about different topics such as Javascript, React and so on. I will try to make many open sources and share to the community.

Best Regards,
Hiep

Forem Open with the Forem app