Behavioral Patterns

Preview — 3 of 10 questions

What does the Builder pattern do?

javascript
// Too many parameters, hard to use
class Pizza {
  constructor(size, cheese, pepperoni, mushrooms, onions, basil, oregano) {
    this.size = size;
    this.cheese = cheese;
    this.pepperoni = pepperoni;
    this.mushrooms = mushrooms;
    this.onions = onions;
    this.basil = basil;
    this.oregano = oregano;
  }
}

// Usage (confusing which parameter is which)
const pizza = new Pizza("large", true, true, false, true, false, true);
AConstructs buildings or structures.
BSeparates object construction from its representation, allowing flexible creation.
CBuilds HTML documents.
DPrevents object creation.

What does the Mediator pattern do?

javascript
// Each control talks to others directly
class Button {
  click() {
    this.dialogBox.okClicked();
    this.textBox.enable();
    this.checkbox.update();
  }
}

class DialogBox {
  okClicked() { }
}

class TextBox {
  enable() { }
}

class Checkbox {
  update() { }
}

// Objects are tightly coupled; hard to test individually
AMediates disputes between objects.
BReduces coupling between objects by having them communicate through a mediator.
CPrevents communication between objects.
DCreates mediation agreements.

What does the Visitor pattern do?

javascript
// Objects (don't need to know about operations)
class File {
  accept(visitor) {
    return visitor.visitFile(this);
  }
}

class Directory {
  constructor() {
    this.children = [];
  }
  
  add(item) {
    this.children.push(item);
  }
  
  accept(visitor) {
    return visitor.visitDirectory(this);
  }
}

// Visitors (operations)
class FileSizeVisitor {
  visitFile(file) {
    return file.size || 0;
  }
  
  visitDirectory(directory) {
    return directory.children.reduce((total, child) => {
      return total + child.accept(this);
    }, 0);
  }
}

class FileNameVisitor {
  visitFile(file) {
    return file.name;
  }
  
  visitDirectory(directory) {
    return directory.children.map(child => child.accept(this));
  }
}

// Usage
const dir = new Directory();
dir.add(Object.assign(new File(), { name: "file1.txt", size: 100 }));
dir.add(Object.assign(new File(), { name: "file2.txt", size: 200 }));

// Calculate size
const sizeVisitor = new FileSizeVisitor();
console.log(dir.accept(sizeVisitor)); // 300

// Get file names
const nameVisitor = new FileNameVisitor();
console.log(dir.accept(nameVisitor)); // ["file1.txt", "file2.txt"]
ARepresents a visitor accessing an object.
BSeparates algorithms from the objects they operate on.
CPrevents visitors from accessing objects.
DCreates visitor tracking system.

Sign up free to play

Answer all 10 questions (7 more), see explanations for every answer, and track your score.