Last active
December 20, 2018 12:58
-
-
Save brunnerh/a74b172a32bf3c236c9052624670b4ee to your computer and use it in GitHub Desktop.
Sketch of how to prevent construction of conceptually abstract superclass.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class X | |
{ | |
constructor() | |
{ | |
if (Object.getPrototypeOf(Object.getPrototypeOf(this)) != X.prototype) | |
throw new Error("Cannot construct X directly."); | |
} | |
static create(type) | |
{ | |
switch (type) | |
{ | |
case 1: | |
return new A(); | |
case 2: | |
return new B(); | |
} | |
} | |
} | |
// (Use module and do not export subclasses or nest them inside `create`/an IIFE to prevent direct construction.) | |
class A extends X {} | |
class B extends X {} | |
// [test code] | |
const log = exec => | |
{ | |
console.log(`Executing: ${exec.toString()}`); | |
try | |
{ | |
const value = exec(); | |
console.log('Result:', value); | |
} | |
catch (e) | |
{ | |
console.error('Execution failed:', e.message); | |
} | |
console.log(); | |
}; | |
log(() => X.create(1)); | |
log(() => X.create(2)); | |
log(() => new A()); | |
log(() => new B()); | |
log(() => new X()); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment