...
Creating a singleton class requires creating a static class property, and then setting the value of that property to this
. Then when the constructor runs you check for that static property first and try to return that instead of a whole new classreturn it if it has already been created.
Once you implement this pattern you can feel free to run new GumbandServiceGumbandSDKWrapper()
(your wrapper class) multiple times in your code to get reference to any properties and methods you desire without duplicating calls to new Gumband()
.
Code Block | ||
---|---|---|
| ||
// File: your-gumband-project/gumband/gumband-service-wrapper.js // Imports const { Gumband } = require("@deeplocal/gumband-node-sdk"); /** * A class that wraps the Gumband SDK and handles websocket messages * that come from the Gumband Cloud. */ class GumbandServiceGumbandSDKWrapper { /** * A reference to the Gumband SDK instance. */ gumbandSDK; // Static variable to hold the singleton instance static instance; constructor() { // Check if an instance already exists // If it does, return the existing instance if (GumbandService.instance) { return GumbandService.instance; } // Create the Gumband SDK instance this.gumbandSDK = new Gumband(...contructorArgs); // Store the instance in the static variable GumbandService.instance = this; } // ... your other class methods } // Export the GumbandServiceGumbandSDKWrapper class module.exports = { GumbandServiceGumbandSDKWrapper }; |