No Esta Facil
  • 🌎About No Esta Facil
    • πŸ‘¨β€πŸ’»GitHub
    • πŸ“·Photography
    • πŸ—£οΈMy Speaker Bio
    • 🀝Disclaimer
    • πŸ“ˆGuilt Pile
      • Principal.dev
      • Tech Rocks Asia
  • πŸ“šBook Reviews
    • Sports
      • Ben Hogan's Five Lessons
    • Productivity
      • Smart Brevity
      • Nine Lies About Work: A Freethinking Leader’s Guide to the Real World
      • Think Again
      • Mastery
      • Talk Like Ted
      • The Hard Thing About Hard Things
      • The Courage to Be Disliked by Fumitake Koga and Ichiro Kishimi
    • Classic Texts
      • The Book of five rings
    • Technology
      • Amplifying Your Effectiveness: A Gem in Professional Growth Literature
      • AI Superpowers: China, Silicon Valley, and the New World Order
      • The Age of Agile
    • Business
      • Start with No by Jim Camp
      • Zero to One: Notes on Startups, or How to Build the Future by Peter Thiel
    • Health, fitness, and dieting
      • Outlive
    • Culture
      • Solito by Javier Zamora
  • Daily Goods
    • Continuous Education
      • Expanding Your Vocabulary
    • 🌡Cultura
      • Food
        • BBQ’n Like a Pro: Rub Recipes for Pork, Brisket, and Chicken
        • The Ultimate Mashed Potatoes with Bacon and Roasted Garlic
  • 🏌️My Golf Journey
    • Teeing off at ...
      • Oaks Quarry Golf, Riverside, CA
      • Education City Golf Club, Qatar, Doha
      • The Links at Spanish Bay, Pebble Beach, CA
      • Bayonet, Seaside, CA
      • Alta Sierra Country Club, Grass Valley, CA
    • Training
  • πŸ“Monthly Highlights [in TL;DR format]
    • FY23
      • El PeriΓ³dico - July 2023
      • El PeriΓ³dico - December 2023
      • El PeriΓ³dico - April 2023
      • El PeriΓ³dico - March 2023
      • El PeriΓ³dico - February 2023
      • El PeriΓ³dico - January 2023
      • El PeriΓ³dico - December 2022
    • FY24
      • January 2024
      • February 2024
      • March 2024
      • April 2024
    • FY25
  • πŸ‘¨β€πŸ’»The section on Software Engineering
    • ChatGPT Prompts
      • Usages
        • What are some flutter architectures?
      • Prompt Templates
        • Answer Misconceptions
    • Conferences and Bootcamps
      • Google Cloud BootCamp
      • Principal Developer Masterclass
    • Customer Engagement
      • Awards - Customer Hero
    • Engineering Manager
      • Mobile Application Development
        • Flutter Journal
          • App Release Resources
        • Accelerate Your Go-to-Market Strategy with Flutter
      • Understanding the Meaning of Software Requirements
      • Design Principles
        • Coupling
        • Routine
        • Software Design
          • The Trinity of Software Architecture: Coupling, Cohesion, and Information Hiding
      • General
        • Engineering Meetings
          • Steering the Conversation: Effective Strategies for Keeping Meetings Focused and Productive
    • Project Owner
      • Project Pressure, It Happens!
      • Strategic Leadership and Planning
    • Software Engineering
      • Overview
      • Design Patterns
        • Categories of Design Patterns
        • Choosing the Right Design Pattern for Problem-Solving in Programming
        • Singleton
      • Programming Languages
        • JavaScript
      • Toolkits
        • iTerm2
        • Developing on a Windows 11 machine
          • Setting up Typscript env
        • VS Code Extension
        • HTTPie
      • Best Practices
        • Pull Requests (PR's)
    • Solutions Engineer
      • Communication with executives
      • SE Toolkit
        • The Importance of Retros in Integration Processes
        • Meetings
          • Preparing for a Customer Meeting (Project-Based or Recurring)
          • Conducting a Productive Customer Meeting
          • Prepare and Send a Concise and Actionable Meeting Summary
            • Meeting Summary Template
        • Documentation
          • Adding an important notes section
          • Useful Resources
  • πŸ›«Travel
    • Asia
      • Singapore
      • Japan
      • South Korea
      • China
      • India
    • Caribbean Sea
      • Cuba
    • Europe
      • North America
        • Mexico
          • Guadalajara
        • Canada
    • Oceania
      • Fiji
    • Middle East
      • Dubai
      • Qatar
    • South America
      • Brazil
      • Peru
      • Columbia
    • In the planning stage ...
      • Antarctica
      • Africa
Powered by GitBook
On this page
  1. The section on Software Engineering
  2. Software Engineering
  3. Design Patterns

Singleton

When to use the Singleton Pattern?

Use the Singleton pattern when exactly one object is needed to coordinate others across a system.

Below is an example of a singleton pattern:

class Logger {
  constructor(options = {}) {
    this.level = options.level || 'info'; 
    this.logs = [];
  }

  log(message) {
    this.logs.push(`${this.level}: ${message}`);
    console.log(`${this.level}: ${message}`);
  }

  getLogs() {
    return this.logs;
  }
}

// Instance holder
let instance;

const LoggerFactory = {
  getInstance(options) {
    if (instance === undefined) {
      instance = new Logger(options);
    }
    return instance;
  },
};

// Get the logger instance with a specific log level
const myLogger = LoggerFactory.getInstance({ level: 'debug' });

// Log some messages
myLogger.log('This is a debug message'); 
myLogger.log('Another debug message');

// Get the logger instance again (it will be the same instance)
const anotherLogger = LoggerFactory.getInstance();

// This will also log as 'debug' because it's the same instance
anotherLogger.log('Yet another message'); 

// Get all logs
console.log(anotherLogger.getLogs());

Explanation:

This example creates a Logger class that allows you to log messages with different log levels (e.g., 'debug', 'info', 'error'). The LoggerFactory object ensures that only one Logger instance exists throughout your application.

Here's why this is useful:

  • Centralized Logging: You have a single point of access for logging in your application.

  • Consistent Log Level: The log level is set once when the first instance is created, ensuring consistency in how messages are logged.

  • Access to Log History: The getLogs() method lets you retrieve the logged messages, which can be helpful for debugging or auditing.

"This pattern is beneficial in situations where you want to control how logging happens across your application and maintain a single log history.

Identifying Singletons can be difficult. If you’re importing a large module, you will be unable to recognize that a particular class is a Singleton. As a result, you may accidentally use it as a regular class to instantiate multiple objects and incorrectly update it instead.

Challenging to test. Singletons can be more difficult to test due to issues ranging from hidden dependencies, difficulty creating multiple instances, difficulty in stubbing dependencies, and so on.

Need for careful orchestration. An everyday use case for Singletons would be to store data that will be required across the global scope, such as user credentials or cookie data that can be set once and consumed by multiple components. Implementing the correct execution order becomes essential so that data is always consumed after it becomes available and not the other way around. This may become challenging as the application grows in size and complexity."

PreviousChoosing the Right Design Pattern for Problem-Solving in ProgrammingNextProgramming Languages

Last updated 7 months ago

πŸ‘¨β€πŸ’»