Created
July 9, 2017 12:21
Using Static Class Methods To Generate Concrete Instances Of Abstract Classes In JavaScript And Node.js
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 AbstractThing { | |
// --- | |
// ABSTRACT METHODS. | |
// --- | |
doThis() { | |
throw( new Error( "Abstract method." ) ); | |
} | |
doThat() { | |
throw( new Error( "Abstract method." ) ); | |
} | |
// --- | |
// PUBLIC METHODS. | |
// --- | |
execute() { | |
this.doThis(); | |
this.doThat(); | |
} | |
// --- | |
// STATIC METHODS. | |
// --- | |
// I provide a way to create a concrete implementation of the AbstractThing class | |
// by providing the concrete functions. This is in lieu of creating a base class that | |
// extends the AbstractThing class explicitly. | |
static usingFunctions({ doThis, doThat }) { | |
var implementation = new AbstractThing(); | |
// Override the abstract methods with the given concrete functions. | |
implementation.doThis = doThis; | |
implementation.doThat = doThat; | |
return( implementation ); | |
} | |
} | |
// ----------------------------------------------------------------------------------- // | |
// ----------------------------------------------------------------------------------- // | |
// Create a concrete instance using the two concrete methods (no base class needed). | |
var thing = AbstractThing.usingFunctions({ | |
doThis: function() { | |
console.log( "... do this." ); | |
}, | |
doThat: function() { | |
console.log( "... do that." ); | |
} | |
}); | |
console.log( "Is instance of AbstractThing:", ( thing instanceof AbstractThing ) ); | |
thing.execute(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment