React native- Best way to create singleton pattern

前端 未结 3 1961
滥情空心
滥情空心 2020-12-31 10:32

I am new in react-native coding but have experienced on objective-c and swift coding and want use singleton pattern in react-native. I have tried to find out the solution fr

相关标签:
3条回答
  • 2020-12-31 10:36

    You can use something like that

     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();
    
    0 讨论(0)
  • 2020-12-31 10:42

    Here's my implementation for singleton class...

    Controller.js

    export default class Controller {
        static instance = Controller.instance || new Controller()
    
        helloWorld() {
            console.log("Hello World... \(^_^)/ !!")
        }
    }
    

    Usage:

    import Controller from 'Controller.js'
    
    Controller.instance.helloWorld()
    
    0 讨论(0)
  • 2020-12-31 11:00

    The singleton pattern isn't used much in the JS ecosystem. What you should look into is http://mobx.js.org. MobX is a library that allows you to create observable objects to store data for your apps. You instantiate one store for each domain you please and make edits to that store to change app state.

    0 讨论(0)
提交回复
热议问题