Last active
April 2, 2016 13:28
-
-
Save SuperstrongBE/32f8511d2254ccb9eab59cbb45f253aa to your computer and use it in GitHub Desktop.
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
/*-------------------------------------- | |
* Original Gist by dimdimbe : https://gist.github.com/dimdimbe/37abbe5b95bbee800dac94b1e6bba144 | |
* After Further reading, it seem's that require break the singleton pattern. | |
* By the nature of the require cache system, the internal Instance of singleton is preserved... until Garbage collector is triggered. | |
* The most simple workaround is to "polute" the global scope to store the singleton internal instance, | |
* global variables are never disposed of by the GC. | |
/*-------------------------------------- | |
var SocketInstance = null | |
; | |
/** | |
@var: __socketSingletonInstance. | |
@description: Internal singleton instance, never call this via global use getInstance instead | |
*/ | |
global.__socketSingletonInstance = null ; | |
/** | |
@class: theObject. | |
@description: Factory Function object. | |
*/ | |
SocketInstance = function(port){ | |
// Add some object or var | |
var _singletonInstance = {}; | |
_singletonInstance.port = port; | |
_singletonInstance.instanceId = Math.random().toString(16).substr(2, 8); | |
_singletonInstance.socket = require('socket.io').listen(port); | |
return _singletonInstance; | |
}; | |
/** | |
@function: getInstance. | |
@description: Return the internal instance, create it if is null | |
*/ | |
function _getInstance(port){ | |
if(!global.__socketSingletonInstance || port){ | |
global.__socketSingletonInstance = new SocketInstance(port); | |
console.log ('create a new instance of port'); | |
} | |
return global.__socketSingletonInstance; | |
} | |
module.exports = { | |
getInstance:_getInstance | |
}; | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment