Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create new instance from singleton

Intro:

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.

Question:

Is there any way to generate new instances of the singleton without modifying the original code?

What I've done:

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.

like image 201
Kaizo Avatar asked Jul 10 '13 12:07

Kaizo


People also ask

Can you create new instance of singleton class?

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.

How do I create a multiple instance of a singleton class?

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.

Can Singleton have multiple instances?

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.


1 Answers

The solution: use the constructor function from the prototype.

var newMyCollection = new (Object.getPrototypeOf(myCollection).constructor);
like image 155
Kaizo Avatar answered Oct 05 '22 23:10

Kaizo