I have some legacy code that creates a singleton:
define(['backbone', 'MyModel'], function (Backbone, MyModel) {
var MyCollection = Backbone.Collection.extend({
model: MyModel,
initialize: function () {
//...
}
});
return new MyCollection();
});
And for test purposes I need to generate new instances to inject them as dependeces.
Is there any way to generate new instances of the singleton without modifying the original code?
I came with a solution: add the class as a property of the instace
initialize: function () {
this.ClassObject = MyCollection;
//...
}
and then instantiate it
var myCollection = require('myCollection');
var myCollectionInstance = new myCollection.ClassObject();
This solution modifies the class and I'd like to avoid it.
I also tryed creating a copy of the singleton:
function generateNewCollection() {
var F = function () {};
F.prototype = myCollection;
return new F();
}
It generates a new instance but it doesn't create new instances of its dependences, so the environment is still dirty for the next tests.
You can make the new instance of the Singleton class by changing the constructor visibility as public in run-time and create new instance using that constructor.
Singleton patten means only one instance is allowed. So there is no question of creating multiple instances. Though there are some hacks and workarounds like Serializing the Object and De Serializing it back or using different Class loaders but again it violates the basic principle why Singleton pattern is created for.
The Singleton's purpose is to control object creation, limiting the number to one but allowing the flexibility to create more objects if the situation changes. Since there is only one Singleton instance, any instance fields of a Singleton will occur only once per class, just like static fields.
The solution: use the constructor function from the prototype.
var newMyCollection = new (Object.getPrototypeOf(myCollection).constructor);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With