Structural Patterns — Series 3

Preview — 3 of 10 questions

A notification system must support Alert/Reminder messages over Email/SMS/Push. Why is Bridge preferable to subclassing?

ABridge caches instances, so fewer objects are allocated.
BBridge lets a subclass override the transport at runtime, which inheritance cannot do.
CInheritance multiplies: two message kinds × three transports means six classes, and each new transport adds two more. Bridge splits the abstraction from the implementation so the two dimensions vary independently — 2 + 3 classes composed at runtime.
DBridge is a creational pattern, so it also handles construction.

What is logged?

javascript
const cache = new Map();
const glyph = (ch) => {
  if (!cache.has(ch)) cache.set(ch, { ch });
  return cache.get(ch);
};
const draw = (ch, x) => ({ glyph: glyph(ch), x });

const a = draw('a', 0);
const b = draw('a', 10);

console.log(a.glyph === b.glyph, a.x === b.x, cache.size);
Atrue false 1
Bfalse false 2
Ctrue true 1
Dtrue false 2

What is logged?

javascript
const Counter = (() => {
  let n = 0;
  const inc = () => ++n;
  const reset = () => { n = 0; };
  return Object.freeze({ inc, reset });
})();

Counter.inc();
Counter.inc();
const before = Counter.inc();
Counter.inc = () => 999;

console.log(before, Counter.inc(), typeof Counter.reset, Object.isFrozen(Counter));
A3 999 function true
B1 999 undefined false
C3 4 undefined true
D3 4 function true

Sign up free to play

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