React native is the best way to create a singleton template.

I am new to reaction-based coding, but have tested objective-c and fast coding, and want to use a singleton pattern in reaction-native. I tried to find a solution from another StackOverflow answer, but most of them only create singleton functions, as shown below:

var Singleton = (function () {
    var instance;

    function createInstance() {
        var object = new Object("I am the instance");
        return object;
    }

    return {
        getInstance: function () {
            if (!instance) {
                instance = createInstance();
            }
            return instance;
        }
    };
})();

function run() {

    var instance1 = Singleton.getInstance();
    var instance2 = Singleton.getInstance();

    alert("Same instance? " + (instance1 === instance2));  
}

As we see in the above code, we create a singleton function not class. Please let me know if there is any way to create a singleton class and pass multiple variables in this class as objective-c or fast. Note. Please also let me know if I go in the wrong direction.

+3
source share
3

singleton class...

Controller.js

export default class Controller {
    static sharedInstance = Controller.sharedInstance == null ? new Controller() : this.sharedInstance

    printHelloWorld() {
        console.log("\n\tHello World... \(^_^)/ !!")
    }
}

:

import Controller from 'Controller.js'

Controller.sharedInstance.printHelloWorld()
+4

-

 class SingletonClass {

  static instance = null;
  static createInstance() {
      var object = new SingletonClass();
      return object;
  }

  static getInstance () {
      if (!SingletonClass.instance) {
          SingletonClass.instance = SingletonClass.createInstance();
      }
      return SingletonClass.instance;
  }
}

var instance1 = SingletonClass.getInstance();
var instance2 = SingletonClass.getInstance();
+3

JS. , http://mobx.js.org. MobX - , . , , , .

0

Source: https://habr.com/ru/post/1675770/


All Articles