JavaScript Design Patterns

Published on Author craigzearfossLeave a comment

Constructor Pattern

Object constructors are used to create specific types of objects.
Examples:

var newObject = {};
// or
var newObject = Object.create( Object.prototype );
// or
var newObject = new Object();

Module Pattern

Provides both private and public encapsulation.

Used to emulate the concept of classes.

Options for implementing modules include:

  • The Module pattern
  • Object literal notation (doesn’t require instantiation using the new operator)
  • AMD modules
  • CommonJS modules
  • ECMAScript Harmony modules

Advantages:

  • Cleaner for developers coming from an object-oriented background than the idea of true encapsulation.
  • It supports private data.

Disadvantages:

  • Access both public and private members differently.
  • Can’t access private members in methods that are added to the object at a later point.
  • Inability to create automated unit tests for private members and additional complexity when bugs require hot fixes.

Revealing Module Pattern

Define all functions and variables in private scope and return an anonymous object with pointers to the private functionality we wish to reveal as public.

Advantages:

  • Allows the syntax of our scripts to be more consistent.

Disadvantages:

  • If a private function refers to a public function, that public function can’t be overridden if a patch is necessary.

Singleton Pattern

Restricts instantiation of a class to a single object.

Differs from static classes (or objects) because their initialization can be delayed.

When used it may signal that modules in a system are either tightly coupled or that logic is overly spread across multiple parts of a codebase.


Observer Pattern

An object (known as a subject) maintains a list of objects depending on it (observers), automatically notifying them of any changes to state.

When a noteworthy event occurs the subject broadcasts a notification to the observers.

Subject can remove observers so they are no longer notified.

Definitions:

  • Subject: maintains a list of observers, facilitates adding or removing observers.
  • Observer: provides an update interface for objects that need to be notified of a Subject’s changes of state.
  • ConcreteSubject: broadcasts notifications to observers on changes of state, stores the state of ConcreteObservers.
  • ConcreteObserver: stores a reference to the ConcreteSubject, implements an update interface for the Observer to ensure state is consistent with the Subject’s.

Differences between an Observer and a Publish/Subscribe pattern.

  • Observer: object must subscribe to the subject.
  • Publish/Subscribe: topic/event channel sits between the subscribers and the publisher. (Allows any subscriber with an appropriate event handler to register for and receive topic notifications.)

Advantages:

  • Allows breaking an application into smaller, more loosely coupled blocks.
  • Can maintain consistency between related objects without making classes tightly coupled.
  • Dynamic relationships can exist between observers and subjects.

Disadvantages:

  • Can become difficult to guarantee that particular parts of our applications are functioning as we may expect.
  • Due to the dynamic relationship between subscribers and publishers, the update dependency can be difficult to track.

Mediator Pattern

A Mediator is an object that coordinates interactions between multiple objects.

An event aggregator is designed to deal with events whereas a mediator only uses them because it’s convenient.

An event aggregator uses “fire and forget” but a mediator pays attention to a known set of input or activities.

A mediator is best applied when objects have an indirect working relationship, and business logic or workflow needs to dictate the interactions and coordination of these objects.

Advantages:

  • Reduces communication channels between objects or components from many-to-many to just many-to-one.

Disadvantages:

  • Introduces a single point of failure.

Prototype Pattern

Creates objects based on a template of an existing object through cloning.

Advantages:

  • Easy way to implement inheritance.
  • We’re working with the prototypal strengths JavaScript has to offer natively rather than attempting to imitate features of other languages.
  • Object.create also allows us to easily implement advanced concepts such as differential inheritance where objects are able to directly inherit from other objects.

Disadvantages:

  • Can cause trouble when enumerating properties of objects.

Command Pattern

Aims to encapsulate method invocation, requests or operations into a single object and gives the ability to both parameterize and pass method calls around that can be executed at our discretion.

Separates the responsibilities of issuing commands from anything executing commands.


Facade Pattern

Provides a higher-level interface to a larger body of code, hiding its true underlying complexity.

Can often be seen in JavaScript libraries like jQuery.

Disadvantages:

  • Be aware of any performance costs involved and make a call on whether they are worth the level of abstraction offered.

Factory Pattern

Creates objects but doesn’t explicitly require us use a constructor.

When to use:

  • Object or component setup involves a high level of complexity.
  • When need to easily generate different instances of objects depending on the environment we are in.
  • When working with many small objects or components that share the same properties.
  • When composing objects with instances of other objects that need only satisfy an API contract (aka, duck typing) to work. This is useful for decoupling.

When not to use:

  • Can introduce an unnecessarily great deal of complexity to an application.

An Abstract Factory pattern aims to encapsulate a group of individual factories with a common goal. It separates the details of implementation of a set of objects from their general usage.


Mixin Pattern

Classes which offer functionality that can be easily inherited by a sub-class or group of sub-classes for the purpose of function re-use.

Sub-classing is a term that refers to inheriting properties for a new object from a base or superclass object.
Advantages:

  • Decreases functional repetition and increasing function re-use.
  • Injecting functionality into an object prototype may lead to both prototype pollution and a level of uncertainty regarding the origin of our functions.

Decorator Pattern

Offered the ability to add behaviour to existing classes in a system dynamically.

Not heavily tied to how objects are created but instead focuses on the problem of extending their functionality.

An interface is a way of defining the methods an object should have, however, it doesn’t actually directly specify how those methods should be implemented.

The biggest problem with interfaces is that, as there isn’t built-in support for them in JavaScript.

An Abstract Decorator class is defined with default methods required to implement an interface, which the rest of the options will sub-class.

Advantages:

  • Flexible and avoids needing to rely on large numbers of subclasses.

Disadvantages:

  • If poorly managed, it can significantly complicate application architecture as it introduces many small, but similar objects into the namespace.

Flyweight Pattern

Aims to minimize the use of memory in an application by sharing as much data as possible with related objects.


Reference:

Leave a Reply

Your email address will not be published. Required fields are marked *