DEV Community

loading...

Design Patterns: Singleton

Terry Threatt
🖥 Software Engineer
・2 min read

This week I came across a Youtube video discussing the need to understand design patterns as a developer. After learning the syntax of a language, then wrapping your head around data structures and algorithms, You should next learn about design patterns to be a really effective developer.

What are Design Patterns?

Design patterns are common design structures or templates that make the object-orientated design more efficient. Learning design patterns make it easy to recognize and apply these useful techniques to quickly solve common recurring problems.

Importance & Types

These patterns can be helpful in making you more productive by streamlining solutions to problems that have been solved and can help produce known optimized code solutions.

There are three types of design pattern categories that include Creational, Structural, Behavioral design patterns. There are at least 23 different design patterns and they could be explained in-depth in this highly popular design pattern book.

Singleton Pattern

The Singleton design pattern is a creational design pattern type that is useful to control the creation process and restrict the instantiation to only one object.

This pattern is great for speeding up the production process and being a single source of truth or state changes. Jquery is a real-world use-case of this design pattern.

var singletonPattern = (function() {
  var instance;
  function init() {
    // Singleton
    function privateMethod() {
      console.log('privateMethod');
    }
    var privateVariable = 'this is private variable';
    var privateRandomNumber = Math.random();
    return {
      publicMethod: function() {
        console.log('publicMethod');
      },
      publicProperty: 'this is public property',
      getRandomNumber: function() {
        return privateRandomNumber;
      }
    };
  }

  return {
    // Get the singleton instance if one exists
    // or create if it doesn't
    getInstance: function() {
      if (!instance) {
        instance = init();
      }
      return instance;
    }
  };
})();

// Usage:
var single = singletonPattern.getInstance();
var single2 = singletonPattern.getInstance();
console.log(single === single2) // true 
Enter fullscreen mode Exit fullscreen mode

Let's chat about Design Patterns

This should give you more understanding of design patterns and how to structure a Singleton Pattern. If you enjoyed this post feel free to leave a comment about your thoughts and experiences working with design patterns.

Happy Coding,
Terry Threatt

Discussion (0)