[英]Create a singleton class with react native
我發現有不同的主題說明了如何創建單例,但是沒有一個對我有用。 這是本文的一個例子
export default class Credentials {
static myInstance = null;
_userID = "";
static getInstance() {
if (myInstance == null) {
myInstance = new Credentials();
}
return myInstance;
}
getUserID() {
return this._userID;
}
setUserID(id) {
this._userID = id;
}
}
當我調用Credentials.getInstance()
收到警告
找不到變量myInstance
JS沒有像靜態編譯語言那樣的隱式字段查找。 您需要在類上明確查找變量:
class Credentials {
static myInstance = null;
static getInstance() {
if (Credentials.myInstance == null) {
Credentials.myInstance = new Credentials();
}
return Credentials.myInstance;
}
}
請注意這種方法,因為它並不是真正的單例,因為JS沒有正確的類封裝。
您可以直接輕松地更改實例:
Credentials.myInstance = 'something else';
帶有封裝的正確單例應該通過閉包實現:
const Credentials = (() => {
let myInstance = null;
return class Credentials {
static getInstance() {
if (myInstance == null) {
myInstance = new Credentials();
}
return myInstance;
}
}
})()
我認為最干凈,最簡單的解決方案是“ ES6單例模式”(不確定該模式是否有正式名稱)。
您將實例導出為默認實例,並且在所有導入實例時都得到相同的實例。 這取決於對模塊require進行緩存的事實。
您將創建您的類並像這樣導出:
class Credentials {
constructor() {
this._userID = "";
}
get userID() {
return this._userID;
}
set userID(userID) {
this._userID = userID;
}
}
export default new Credentials();
無論將其導入到何處,都會得到相同的實例:
import credentials from './credentials';
對於JS中的任何單例實例而言,這應該足夠了。
現在,無論您在何處導入此文件,都將使用相同的實例。 您可以通過在班級中添加日期並在導入日期的各個位置進行訪問來進行交叉檢查。
import { SomeClass } from 'some-class'
let singletonInstance;
if (!singletonInstance) {
singletonInstance = new SomeClass();
// singletonInstance.time = new Date();
}
export default singletonInstance;
然后使用導入
import singletonInstance from './above-code-file'
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.