React native - 创建单例模式的最佳方式 [英] React native- Best way to create singleton pattern

查看:32
本文介绍了React native - 创建单例模式的最佳方式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 react-native 编码的新手,但在 Objective-c 和 swift 编码方面有经验,希望在 react-native 中使用单例模式.我试图从其他 StackOverflow 答案中找出解决方案,但其中大多数只创建单例函数,如下代码:

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 from other StackOverflow answer but most of them are creating only singleton functions as below code:

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));  
}

正如我们在上面的代码中看到的,我们创建的是单例函数而不是类.请让我知道是否有任何方法可以创建单例类并将该类中的多个变量作为objective-c 或swift 传递.注意:如果我走错了方向,也请通知我.

As we can see in above code here we are creating singleton function not class. Please let me know if any way to create singleton class and pass multiple variables in that class as objective-c or swift. Note: Please also notify me if I am going in the wrong direction.

推荐答案

这是我对单例类的实现...

Here's my implementation for singleton class...

Controller.js

Controller.js

export default class Controller {
    static instance = Controller.instance || new Controller()

    helloWorld() {
        console.log("Hello World... \(^_^)/ !!")
    }
}

用法:

import Controller from 'Controller.js'

Controller.instance.helloWorld()

这篇关于React native - 创建单例模式的最佳方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆