当前位置:   article > 正文

flutter 类单例模式_flutter 单例模式实现

flutter 单例模式实现
你需要构造函数不是每次都创建一个新的对象时,使用factory关键字。	

class 类名 {
  单例公开访问点
  factory 类名() =>_静态获取单例的方法()
  
  静态私有成员,没有初始化
  static 类名 _单例名;
  
  私有构造函数
  类名._构造函数名称() { 若要初始化}

  对外暴露的单例
  static 类名 _静态获取单例的方法() {
    if (_单例名 == null) {
      _单例名 = 类名._构造函数名称();
    }
    return _单例名;
  }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20

代码示例:

class SomeSharedInstance {
  // 单例公开访问点
  factory SomeSharedInstance() =>_sharedInstance()
  
  // 静态私有成员,没有初始化
  static SomeSharedInstance _instance;
  
  // 私有构造函数
  SomeSharedInstance._() {
    // 具体初始化代码
  }

  // 静态、同步、私有访问点
  static SomeSharedInstance _sharedInstance() {
    if (_instance == null) {
      _instance = SomeSharedInstance._();
    }
    return _instance;
  }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20

代码示例:

/// Mianyang Qingmu Software Technology Co., Ltd. <br>
/// Copyright (C) 2014-2020 All Rights Reserved. <br>
/// Website: http://www.qmrjkj.com <br>
/// Author: huanghonghao@qmrjkj.com <br>
/// Date: 2020-09-08 <br>
/// Time: 16:20 <br>

import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';

///屏幕适配方案封装
class ScreenAdaptUtil {
  factory ScreenAdaptUtil() => _instance;
  ScreenAdaptUtil._internal();
  static final ScreenAdaptUtil _instance = ScreenAdaptUtil._internal();

  ///[width]为设计稿的宽,[height]为设计稿的高,[isAllowFontScaling]为是否允许字体缩放
  static void init(
      BuildContext context, num width, num height, bool isAllowFontScaling) {
    ScreenUtil.init(context,
        width: width, height: height, allowFontScaling: isAllowFontScaling);
  }

  /// 设置宽度
  static num setWidth(num width) {
    return ScreenUtil().setWidth(width);
  }

  /// 设置宽度
  static num setHeight(num height) {
    return ScreenUtil().setHeight(height);
  }

  /// 设置字体尺寸
  static num setFontSize(num fontSize) {
    return ScreenUtil().setSp(fontSize);
  }
}

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:【wpsshop博客】
推荐阅读
相关标签
  

闽ICP备14008679号