React native- Best way to create singleton pattern

前端 未结 3 1974
滥情空心
滥情空心 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();
    

提交回复
热议问题