圖文詳解Flutter單例的實現(xiàn)
前言
作為最簡單的一種設(shè)計模式之一,對于單例本身的概念,大家一看就能明白,但在某些情況下也很容易使用不恰當(dāng)。相比其他語言,Dart 和 Flutter 中的單例模式也不盡相同,本篇文章我們就一起探究看看它在 Dart 和 Flutter 中的應(yīng)用。
Flutter(able) 的單例模式
一般來說,要在代碼中使用單例模式,結(jié)構(gòu)上會有下面這些約定俗成的要求:
- 單例類(Singleton)中包含一個引用自身類的靜態(tài)屬性實例(instance),且能自行創(chuàng)建這個實例。
- 該實例只能通過靜態(tài)方法 getInstance() 訪問。
- 類構(gòu)造函數(shù)通常沒有參數(shù),且被標(biāo)記為私有,確保不能從類外部實例化該類。
回顧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}'); }
運行效果
測試二
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}'); }
運行效果
總結(jié)
到此這篇關(guān)于Flutter單例實現(xiàn)的文章就介紹到這了,更多相關(guān)Flutter單例實現(xiàn)內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Android項目實現(xiàn)短信的發(fā)送、接收和對短信進行攔截
本篇文章主要介紹了Android項目實現(xiàn)短信的發(fā)送、接收和對短信進行攔截,這是學(xué)習(xí)Android比較入門的東西,有需要的可以了解一下。2016-10-10Android高手進階教程(二十二)之Android中幾種圖像特效處理的集錦匯總!!
本篇文章主要介紹了Android中幾種圖像特效處理,比如圓角,倒影,還有就是圖片縮放,Drawable轉(zhuǎn)化為Bitmap,Bitmap轉(zhuǎn)化為Drawable等,有需要的可以了解一下。2016-11-11Android 通過SQLite數(shù)據(jù)庫實現(xiàn)數(shù)據(jù)存儲管理
SQLiteOpenHelper 是Android 提供的一個抽象工具類,負(fù)責(zé)管理數(shù)據(jù)庫的創(chuàng)建、升級工作。本文主要介紹了如何使用SQLite數(shù)據(jù)庫實現(xiàn)對數(shù)據(jù)進行存儲管理,感興趣的可以了解一下2021-11-11Android編程之Application設(shè)置全局變量及傳值用法實例分析
這篇文章主要介紹了Android編程之Application設(shè)置全局變量及傳值用法,結(jié)合實例形式較為詳細的分析了全局變量及傳值的相關(guān)技巧,具有一定參考借鑒價值,需要的朋友可以參考下2015-12-12