flutter 类单例模式

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

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

  对外暴露的单例
  static 类名 _静态获取单例的方法() {
    if (_单例名 == null) {
      _单例名 = 类名._构造函数名称();
    }
    return _单例名;
  }
}

代码示例:

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

  // 静态、同步、私有访问点
  static SomeSharedInstance _sharedInstance() {
    if (_instance == null) {
      _instance = SomeSharedInstance._();
    }
    return _instance;
  }
}

代码示例:

/// 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);
  }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值