日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

圖文詳解Flutter單例的實現_Android

更新時間: 2021-11-12 編程語言

前言

作為最簡單的一種設計模式之一,對于單例本身的概念,大家一看就能明白,但在某些情況下也很容易使用不恰當。相比其他語言,Dart 和 Flutter 中的單例模式也不盡相同,本篇文章我們就一起探究看看它在 Dart 和 Flutter 中的應用。

Flutter(able) 的單例模式

一般來說,要在代碼中使用單例模式,結構上會有下面這些約定俗成的要求:

  • 單例類(Singleton)中包含一個引用自身類的靜態屬性實例(instance),且能自行創建這個實例。
  • 該實例只能通過靜態方法 getInstance() 訪問。
  • 類構造函數通常沒有參數,且被標記為私有,確保不能從類外部實例化該類。

回顧iOS,單例的寫法如下:

static JXWaitingView *shared;

+(JXWaitingView*)sharedInstance{
  static dispatch_once_t onceToken;
  dispatch_once(&onceToken, ^{
      shared=[[JXWaitingView alloc]initWithTitle:nil];
  });
  return shared;
}

其目的是通過dispatch_once來控制【初始化方法】只會執行一次,然后用static修飾的對象來接收并返回它。所以核心是只會執行一次初始化。

創建單例

創建單例的案例

class Student {
  String? name;
  int? age;
  //構造方法
  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}');
}

運行效果

總結

原文鏈接:https://juejin.cn/post/7036634365748576263

欄目分類
最近更新