Design Patterns Flashcards

0
Q

What is a constructor that uses prototypes. How does it relate to basic constructors?

A

It is like basic constructors except things that can be shared amongst all instances are moved to the function’s prototype, like methods.

function ClassName () {
    this.prop = true;
}

ClassName.prototype.meth = …

This better conserves memory that basic constructors.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
1
Q

What is a Basic Constructor? What is its limitations and how do you use it?

A

A basic constructor uses a constructor function to build an object. The object is built from any elements assigned to “this” inside the function. Example:

var Animal = function () {
    this.prop = true;
    this.meth = function () {...};
}
Then to use
var horse = new Animal();

The limitations to Basic Constructors are inheritance is difficult and each object created will have its own copies of the methods (waste of memory).

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

What is the module pattern? Advantages and disadvantages?

A

The module pattern uses closures, giving it private and public elements (unlike constructors). The disadvantage is unit tests can’t access private members, public methods added later can’t access private members, and changing the visibility of a member means you have to change the way the member is used within the module (like if you make member “name” public, you have to change methods from “name” to “this.name”).

The module pattern looks like this:

var module = (function (dependencies) {
    var priv ...
    var pub ...
    return pub;
})(injectDependencies);
// anything assigned to "pub" becomes part of the modules public API.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

What is the Revealing Module Pattern? How is it advantageous over the Module Pattern?

A

The advantage is you define (or reveal) what is public at the end. The advantage is this helps you not have to make changes to your code later if you decide to make something public or private later. Example:

var module = (function (dep) {
    var s, i ...
    return {
        i: i
    };
})(inject);
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

What is the Observer Pattern?

A

“One or more observers are interested in the state of a subject and register their interest with the state by attaching themselves. When something changes in the subject’s state that the observers may be interested in, a notify message is sent which calls the update method in each observer. When the observer is no longer interested in the subject’s state, they can simply detach themselves.” - GoF

Put simply, you’ll have an object that manages objects that are observing the subject object. You’ll have a subject object that instantiates the object in charge of managing observers, as well as notifies the observers by calling a common method that all observers share, such as “update()”, on each observer object whenever the state changes on the subject object. You’ll then have various observer objects that all have (among other things) an “update()” method for the subject object to call.

It is useful to be aware of the Observer Pattern, in Javascript, we typically use Subscribe/Publish Pattern instead, which is similar but different.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

What is a Singleton Pattern?
Show an example.
Counter-argument to singletons.

A

A Singleton is really a structure, a way to initialize an instance if it hasn’t been created yet, and always return that same instance every time it is requested thereafter. In this way, they make sure there is only ever 1 instance of a class ever made, as well as only creating an instance in the event that it is needed (lazy load). Example:

var Class = require("...");
var singleton = (function () {
    var instance;
    return {
        getInstance: function () {
            if (!instance) instance = new Class();    // this is the essence of singletons
            return instance;
        }
    }
})();

There are valid uses of Singletons, but often times they show that code might be too tightly coupled with other logic, or that logic is overly spread out across multiple parts of our system.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

What is the Publish/Subscribe Pattern? Pros & cons?

A

The Publish/Subscribe pattern allows us to relate objects in a loosely coupled way. It works by placing a topic/event channel in between objects wishing to receive notifications (subscribers) & objects firing the event (publishers). The idea is it avoids dependencies between the 2 sides & you can add as many subscribers, at any time (future proof).

The advantage over the observer pattern is the publish/subscribe pattern does not call any methods directly on the subscribing objects, which means that it makes no assumptions about them, hence why it is a great pattern for loose coupling. This pattern is considered to be one of the most powerful, best suited patterns for decoupled systems.

The disadvantage is publishers cannot gauruntee that subscribers are listening still or functioning properly.

Popular JS libraries like jQuery & Node have pub/sub utilities built in, making it super easy to get started with.

An example in Node:
var EventEmitter = require(“events”).EventEmitter;
<>

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

What is the Prototype Pattern? How is it like the Prototype Constructor pattern?

A

The Prototype pattern uses ES5 Object.create() with an object as the parent/prototype when creating child objects. It is similar to the Prototype Constructor in that properties and methods that can be shared amongst all children are in the prototype chain, thus saving memory; however, instead of using a constructor function, we use Object.create() with an existing parent object. Example:

var parent = { surname : "Chubbs", speak : function () { console.log(this.surname); } }
var child = Object.create(parent);

You could also add custom properties onto the child using the optional second parameter of Object.create:

var second = Object.create(parent, {
    // the syntax is just like Object.defineProperty()
    name : {
        value : "Julie",
        enumerable: true
    }
});
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

What is the Mediator Pattern? What are the benefits?

How does it relate to the Pub/Sub pattern?

A

The Mediator pattern is instead of objects referring to one another directly, a mediator layer is provided as the central point of communication for relating objects. This promotes loose coupling and better code reusability. When your system has too many direct relationships between components, it is usually a good time to integrate the Mediator pattern to centralize the interactions.

The Pub/Sub pattern is similar in that there’s a central point of communication & no methods are called on the individual objects directly (subscribers & publishers); they are usually also similar in that Mediator frameworks use the terms “subscribe” & “publish”. If there is a difference, perhaps it is that pub/sub patterns tend to have objects that are publishers and objects that are subscribers, where mediators will have objects that are doing both (publishing & subscribing).

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

What is the Facade Pattern? What are the pros and cons?

A

Facades expose a simplified public API which hides the larger underlying body of code. For example, a subsystem might be composed of 10 modules which is then exposed to the outer system via a Facade, which contains only a few methods; the outer system would use those few facade methods without ever knowing or needing to know the internal methods and modules being called.

The advantages of a facade is it simplifies the interface of a class and decouples it from the code that uses it; this oftentimes makes implementing code less error prone. The disadvantage is there is a performance cost when implementing a facade, so make sure the added abstraction is worth the performance cost.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

What is the Factory Pattern? What is the alternative, and when would you use a factory over the alternative?
Show an example of using one.

What is an Abstract Factory Pattern?

A

The Factory pattern provides a generic interface for creating multiple types of objects. Example, instead of creating a UI element directly, you might implement a single factory that creates elements for you; you would just specify which element to create and provide any additional arguments.

Most of the time, using a constructor directly is preferred over the complexity of a factory, but factories can be useful when:

  • When object setup is complex
  • When you need to return different instances depending on the environment
  • When working with many small objects that share the same properties
Ex:
// constructors
function Person (options) {}
function Child (options) {}
// factory
function Factory () {}
Factory.prototype.create = function (type, options) {
    var class;
    if (type === "person") class = Person; else class = Child;
    return new class(options);
}

And Abstract Factory encapsulates multiple factories such that they can share a common goal.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

What is the Command Pattern?

A

Instead of invoking an object’s methods directly, the object would contain a method called run() or execute(), where you’d pass in the name of the method and the args of that method you are trying to invoke. The idea is that it makes the coupling of the object invoking the other object looser, so that should you need to change the method being invoked, you could do so more easily since it isn’t ever invoked directly (from the outside). Ex:

var o = {
    meth: function () { ... },
    run: function (name) {
        // test if the method exists and then invoke it with the remaining args
        return this[name] && this[name].apply(o, Array.prototype.slice.call(arguments, 1));
    }
};
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

What is subclassing? Show example in JS.

A

Sub-classing is when a subclass/child inherits properties & methods from a superclass/parent. Subclasses can override parent properties and can call parent methods even after overriding (called method chaining).

Example:

function Parent (name) {
  this.name = name
}
Print.prototype.print = function () { console.log(this.name); }
function Child (name, age) {
  // call parent constructor on `this`
  // (this adds all parent properties directly onto `this`, meaning child.hasOwnProperty("name") => true)
  Parent.call(this, name);
  this.age = age;
}
// this adds the parent's prototype methods to the child's prototype
// Object.create makes it so they don't both point to the same object, which would be bad because then the child could modify the parent's prototype (only parents should be able to modify children)
Child.prototype = Object.create( Parent.prototype );
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

What are Mixins? How can they be implemented in JS?

A

Mixins increase function reuse by allowing you to create objects that inherit part of or all of 1 or more objects. For example:

function Mixin () {}
Mixin.prototype = {
  left : function () { ... },
  right : function () { ... }
};
function Class () {}
// best to create a function to do this dynamically, but...
Class.prototype.left = Mixin.prototype.left;
How well did you know this?
1
Not at all
2
3
4
5
Perfectly