圖文詳解Flutter單例的實(shí)現(xiàn)
前言
作為最簡單的一種設(shè)計(jì)模式之一,對于單例本身的概念,大家一看就能明白,但在某些情況下也很容易使用不恰當(dāng)。相比其他語言,Dart 和 Flutter 中的單例模式也不盡相同,本篇文章我們就一起探究看看它在 Dart 和 Flutter 中的應(yīng)用。

Flutter(able) 的單例模式
一般來說,要在代碼中使用單例模式,結(jié)構(gòu)上會有下面這些約定俗成的要求:
- 單例類(Singleton)中包含一個(gè)引用自身類的靜態(tài)屬性實(shí)例(instance),且能自行創(chuàng)建這個(gè)實(shí)例。
- 該實(shí)例只能通過靜態(tài)方法 getInstance() 訪問。
- 類構(gòu)造函數(shù)通常沒有參數(shù),且被標(biāo)記為私有,確保不能從類外部實(shí)例化該類。

回顧iOS,單例的寫法如下:
static JXWaitingView *shared;
+(JXWaitingView*)sharedInstance{
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
shared=[[JXWaitingView alloc]initWithTitle:nil];
});
return shared;
}
其目的是通過dispatch_once來控制【初始化方法】只會執(zhí)行一次,然后用static修飾的對象來接收并返回它。所以核心是只會執(zhí)行一次初始化。
創(chuàng)建單例
創(chuàng)建單例的案例
class Student {
String? name;
int? age;
//構(gòu)造方法
Student({this.name, this.age});
// 單例方法
static Student? _dioInstance;
static Student instanceSingleStudent() {
if (_dioInstance == null) {
_dioInstance = Student();
}
return _dioInstance!;
}
}
測試單例效果
測試一
import 'package:flutter_async_programming/Student.dart';
void main() {
Student studentA = Student.instanceSingleStudent();
studentA.name = "張三";
Student studentB = Student.instanceSingleStudent();
print('studentA姓名是${studentA.name}');
print('studentB姓名是${studentB.name}');
}
運(yùn)行效果

測試二
import 'package:flutter_async_programming/Student.dart';
void main() {
Student studentA = Student.instanceSingleStudent();
studentA.name = "張三";
Student studentB = Student.instanceSingleStudent();
studentB.name = "李四";
print('studentA姓名是${studentA.name}');
print('studentB姓名是${studentB.name}');
}
運(yùn)行效果

總結(jié)
到此這篇關(guān)于Flutter單例實(shí)現(xiàn)的文章就介紹到這了,更多相關(guān)Flutter單例實(shí)現(xiàn)內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Android項(xiàng)目實(shí)現(xiàn)短信的發(fā)送、接收和對短信進(jìn)行攔截
本篇文章主要介紹了Android項(xiàng)目實(shí)現(xiàn)短信的發(fā)送、接收和對短信進(jìn)行攔截,這是學(xué)習(xí)Android比較入門的東西,有需要的可以了解一下。2016-10-10
Android高手進(jìn)階教程(二十二)之Android中幾種圖像特效處理的集錦匯總!!
本篇文章主要介紹了Android中幾種圖像特效處理,比如圓角,倒影,還有就是圖片縮放,Drawable轉(zhuǎn)化為Bitmap,Bitmap轉(zhuǎn)化為Drawable等,有需要的可以了解一下。2016-11-11
RelativeLayout(相對布局)用法實(shí)例講解
在本文里小編給大家分享了關(guān)于RelativeLayout(相對布局)用法知識點(diǎn)以及對應(yīng)的實(shí)例內(nèi)容,需要的朋友們學(xué)習(xí)下。2019-02-02
Android自定義dialog 自下往上彈出的實(shí)例代碼
本文通過實(shí)例代碼給大家介紹了Android自定義dialog 自下往上彈出效果,代碼簡單易懂,非常不錯(cuò),具有一定的參考借鑒價(jià)值,需要的朋友參考下吧2018-08-08
Android 通過SQLite數(shù)據(jù)庫實(shí)現(xiàn)數(shù)據(jù)存儲管理
SQLiteOpenHelper 是Android 提供的一個(gè)抽象工具類,負(fù)責(zé)管理數(shù)據(jù)庫的創(chuàng)建、升級工作。本文主要介紹了如何使用SQLite數(shù)據(jù)庫實(shí)現(xiàn)對數(shù)據(jù)進(jìn)行存儲管理,感興趣的可以了解一下2021-11-11
Android編程之Application設(shè)置全局變量及傳值用法實(shí)例分析
這篇文章主要介紹了Android編程之Application設(shè)置全局變量及傳值用法,結(jié)合實(shí)例形式較為詳細(xì)的分析了全局變量及傳值的相關(guān)技巧,具有一定參考借鑒價(jià)值,需要的朋友可以參考下2015-12-12

