flutter 单例模式

146 篇文章 1 订阅

总的思想就是:
确保整个应用程序中只有一个 TranslationService 实例。
避免重复创建相同的实例,节省资源。
为整个应用程序提供一个全局访问点,方便在不同地方使用同一个实例。

1.类创建个实例
2.然后用构造函数赋值给实例
3.其他地方调用时返回实例

import 'package:social_im/google_translation/google_translation.dart';

class TranslationService {
//创建私有的静态实例_instance,通过调用私有构造函数 TranslationService._internal() 来初始化这个实例。
  static final TranslationService _instance = TranslationService._internal();

 //这是一个工厂构造函数,它返回已经创建好的 _instance 实例。当我们调用 TranslationService() 时,实际上是在获取这个已经创建好的单例实例。
  factory TranslationService() {
    return _instance;
  }

//这是一个私有的命名构造函数,它被用于创建那个单例实例。通过将构造函数设为私有,我们确保了只有类内部能够创建实例,外部无法直接使用 new TranslationService._internal() 来创建新实例。
  TranslationService._internal();

  final _googleTranslation = GoogleTranslation(
    apiKey: 'YOUR_API_KEY',
    onError: (error) {
      // 处理错误
      print('Translation error: $error');
    },
  );

  //final translationService = TranslationService();
// final translatedText = await translationService.translateText('Hello', 'zh');
// print(translatedText); // 输出翻译后的文本
  Future<String> translateText(String text, String targetLanguage) async {
    final translation = await _googleTranslation.translate(
      text: text,
      to: targetLanguage,
    );
    return translation.translatedText;
  }

  // final detectedLanguage = await translationService.detectLanguage('Hello');
// print(detectedLanguage); // 输出检测到的语言代码
  Future<String> detectLanguage(String text) async {
    final detection = await _googleTranslation.detectLang(text: text);
    return detection.detectedSourceLanguage;
  }
}

第二种方法:

class ZeGoCallPayUtils {

//这一行声明了一个静态变量 _instance,用于存储单例实例。它被声明为可空的 ZeGoCallPayUtils? 类型。
  static ZeGoCallPayUtils? _instance;

//这是一个私有的命名构造函数 _internal()。当这个构造函数被调用时,会执行:_instance = this; 将当前实例赋值给静态变量 _instance。
  ZeGoCallPayUtils._internal() {
    _instance = this;
    PrintUtil.prints('$TAG 初始化数据');
  }

//这是一个工厂构造函数。当你调用 ZeGoCallPayUtils() 时,它会执行以下操作:_instance ?? ZeGoCallPayUtils._internal(); 如果 _instance 不为空,则返回 _instance。如果 _instance 为空,则调用私有构造函数 _internal() 创建一个新实例。
  factory ZeGoCallPayUtils() => _instance ?? ZeGoCallPayUtils._internal();
}

通过这些方式,我们确保了只有一个 ZeGoCallPayUtils 实例会被创建

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值