All quizzesMedium
Structural Patterns — Series 2
Preview — 3 of 10 questions
What pattern is demonstrated here, and what is logged?
javascript
class RemoteControl {
constructor(device) {
this.device = device;
}
togglePower() {
return this.device.isOn() ? this.device.turnOff() : this.device.turnOn();
}
}
class AdvancedRemoteControl extends RemoteControl {
mute() {
return this.device.setVolume(0);
}
}
class Radio {
#on = false;
isOn() {
return this.#on;
}
turnOn() {
this.#on = true;
return 'Radio on';
}
turnOff() {
this.#on = false;
return 'Radio off';
}
setVolume(v) {
return `Radio volume: ${v}`;
}
}
const remote = new AdvancedRemoteControl(new Radio());
console.log(remote.togglePower());
console.log(remote.mute());AThe Adapter pattern — it converts the device's interface to match the remote's expectations; logs "Radio on", "Radio volume: 0".
BThe Decorator pattern — it wraps the device with additional remote-control behavior; logs "Radio on", "Radio volume: 0".
CThe Bridge pattern — it decouples an abstraction (the remote control hierarchy) from its implementation (the device hierarchy) via composition, letting both vary independently; logs "Radio on", "Radio volume: 0".
DThe Bridge pattern; logs "TV on", "TV volume: 0".
What is logged?
javascript
class TreeType {
constructor(name, color, texture) {
this.name = name;
this.color = color;
this.texture = texture;
}
draw(x, y) {
return `Drawing ${this.name} tree at (${x}, ${y})`;
}
}
class TreeTypeFactory {
static #types = new Map();
static getType(name, color, texture) {
const key = `${name}-${color}-${texture}`;
if (!TreeTypeFactory.#types.has(key)) {
TreeTypeFactory.#types.set(key, new TreeType(name, color, texture));
}
return TreeTypeFactory.#types.get(key);
}
}
const forest = [];
function plantTree(x, y, name, color, texture) {
const type = TreeTypeFactory.getType(name, color, texture);
forest.push({ x, y, type });
}
plantTree(1, 1, 'Oak', 'green', 'rough');
plantTree(2, 5, 'Oak', 'green', 'rough');
plantTree(3, 8, 'Pine', 'dark-green', 'smooth');
console.log(forest.length);
console.log(forest[0].type === forest[1].type);
console.log(forest[0].type === forest[2].type);A2, true, false
B3, false, false
C3, true, true
D3, true, false
What is logged?
javascript
const Calculator = (() => {
let result = 0;
function add(n) {
result += n;
}
function subtract(n) {
result -= n;
}
function getResult() {
return result;
}
return {
add,
subtract,
getResult,
};
})();
Calculator.add(10);
Calculator.subtract(3);
console.log(Calculator.getResult());
console.log(typeof Calculator.result);
console.log(Object.keys(Calculator));A7, "number", ["add", "subtract", "getResult", "result"]
B7, "undefined", ["add", "subtract", "getResult"]
C13, "undefined", ["add", "subtract", "getResult"]
D7, "undefined", ["result"]
Sign up free to play
Answer all 10 questions (7 more), see explanations for every answer, and track your score.