Design Patterns
  • Introduction
  • Proto-Pattern
  • Anti-pattern
  • OO Design Principles
  • Classification
  • Creational Design Patterns
    • Singleton
    • Factory
    • Abstract Factory
    • Builder
    • Prototype
  • Structural design patterns
    • Adapter
    • Bridge
    • Composite
    • Decorator
    • Facade
    • Flyweight
    • Proxy
  • Behavioural Design Pattern
    • Chain of Responsibility
    • Command
    • Interpreter
    • Iterator
    • Mediator
    • Memento
    • Observer
    • State
    • Strategy
    • Template Method
    • Visitor
  • Concurrency Design Pattern
  • Architectural Design Pattern
  • Modern Desing Patterns
Powered by GitBook
On this page

Was this helpful?

  1. Creational Design Patterns

Singleton

A class of which only a single instance can exist.

  • A class has only one instance and provides a global point of access.

  • It's usage is high in javascript libraries.

  • It limits the number of instance of particular object to one, a single instance called as singleton.

  • Reduces the need for global variables because it limits namespace collision and associated risk of name collision.

  • Module pattern is manifestation(a symptom) of singleton pattern.

  • Several other patterns, such as, Factory, Prototype, and Facade are frequently implemented as Singletons when only one instance is needed.

EX:
var Singleton = (function () {
    var instance;
 
    function createInstance() {
        var object = new Object("I am the instance");
        return object;
    }
 
    return {
        getInstance: function () {
            if (!instance) {
                instance = createInstance();
            }
            return instance;
        }
    };
})();
 
function run() {
 
    var instance1 = Singleton.getInstance();
    var instance2 = Singleton.getInstance();
 
    alert("Same instance? " + (instance1 === instance2));  
}
PreviousCreational Design PatternsNextFactory

Last updated 5 years ago

Was this helpful?