你需要构造函数不是每次都创建一个新的对象时,使用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);
}
}