Design Patterns Handbook
  • Introduction
  • Creational Patterns
    • Builder
    • Factory
    • Abstract Factory
    • Factory Method
    • Prototype
    • Singleton
    • Object Pool
    • Revealing Constructor
  • Structural Patterns
    • Adapter
    • Composite
    • Proxy
    • Flyweight
    • Facade
    • Bridge
    • Decorator
    • Private Class Data
  • Behavioral Patterns
    • Template Method
    • Mediator
    • Chain Of Responsibility
    • Observer
    • Strategy
    • Command
    • State
    • Visitor
    • Memento
    • Interpreter
    • Null Object
    • Iterator
    • Middleware
  • Clean Code Patterns
    • Extract Method
    • Clarify Responsibility
    • Remove Duplications
    • Keep Refactoring
    • Always Unit Test
    • Create Data Type
    • Comment to Better Name
    • Consistent Naming
    • If-else over ternary operator
    • Composition over Inheritance
    • Too Many Returns
    • Private to Interface
  • Anti Patterns
    • Big Ball of Mud
    • Singleton
    • Mad Scientist
    • Spaghetti Code
    • It Will Never Happen
    • Error Codes
    • Commented Code
    • Abbreviations
    • Prefixes
    • Over Patternized
    • Generic Interface over Function
Powered by GitBook
On this page

Was this helpful?

  1. Creational Patterns

Revealing Constructor

Revealing constructor is used in JavaScript, for example, to implement Promise class. The constructor of Promise class takes function with two parameters (resolve and reject) into constructor. It is perfect way to hide implementation details and there is no way somebody can mess around with resolve and reject after the instance if created.

Example - Read-only event emitter

The emit function of ReadOnlyEmitter can be called only in function that is passed into the constructor.

const EventEmitter = require('events');

class ReadOnlyEmitter extends EventEmitter {
  constructor (executor) {
    super();
    const emit = this.emit.bind(this);
    this.emit = undefined; // hide emit function
    executor(emit);
  }
};

const ticker = new ReadOnlyEmitter((emit) => {
  let tickCount = 0;
  setInterval(() => emit('tick', tickCount++), 1000);
});

ticker.on('tick', (count) => console.log('Tick', count));
PreviousObject PoolNextStructural Patterns

Last updated 5 years ago

Was this helpful?