Structural Patterns

Preview — 3 of 10 questions

What is the difference between Factory and Abstract Factory patterns?

javascript
class ButtonFactory {
  static create(type) {
    if (type === "submit") return new SubmitButton();
    if (type === "cancel") return new CancelButton();
  }
}

const submitBtn = ButtonFactory.create("submit");
AThey are the same thing.
BFactory creates instances of one family of objects; Abstract Factory creates instances of multiple related families.
CFactory is abstract; Abstract Factory is concrete.
DAbstract Factory is deprecated.

What is the Mixin pattern?

javascript
// Mixin 1: Can fly
const CanFly = {
  fly() {
    return `${this.name} is flying`;
  }
};

// Mixin 2: Can swim
const CanSwim = {
  swim() {
    return `${this.name} is swimming`;
  }
};

// Mixin 3: Can bark
const CanBark = {
  bark() {
    return `${this.name} says woof!`;
  }
};

// Create a Duck with multiple mixins
class Duck {
  constructor(name) {
    this.name = name;
  }
}

// Mix in the methods
Object.assign(Duck.prototype, CanFly, CanSwim, CanBark);

const duck = new Duck("Donald");
console.log(duck.fly()); // "Donald is flying"
console.log(duck.swim()); // "Donald is swimming"
console.log(duck.bark()); // "Donald says woof!"
AMixing different programming languages together.
BAdding methods and properties from multiple objects to a single object.
CMixing synchronous and asynchronous code.
DA deprecated pattern not used anymore.

What does the Command pattern do?

javascript
// Command interface
class Command {
  execute() { }
  undo() { }
}

// Concrete commands
class TurnOnLight extends Command {
  constructor(light) {
    super();
    this.light = light;
  }
  
  execute() {
    this.light.turnOn();
  }
  
  undo() {
    this.light.turnOff();
  }
}

class TurnOffLight extends Command {
  constructor(light) {
    super();
    this.light = light;
  }
  
  execute() {
    this.light.turnOff();
  }
  
  undo() {
    this.light.turnOn();
  }
}

// Receiver
class Light {
  turnOn() {
    console.log("Light is on");
  }
  
  turnOff() {
    console.log("Light is off");
  }
}

// Invoker
class RemoteControl {
  constructor() {
    this.commands = [];
  }
  
  execute(command) {
    command.execute();
    this.commands.push(command);
  }
  
  undo() {
    const command = this.commands.pop();
    if (command) command.undo();
  }
}

// Usage
const light = new Light();
const remote = new RemoteControl();

remote.execute(new TurnOnLight(light)); // "Light is on"
remote.execute(new TurnOffLight(light)); // "Light is off"
remote.undo(); // "Light is on"
AExecutes commands in the terminal.
BEncapsulates a request as an object, allowing parameterization and queuing of operations.
CCreates a command-line interface.
DPrevents execution of commands.

Sign up free to play

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