flutter 单例模式

总的思想就是:

确保整个应用程序中只有一个 TranslationService 实例。

避免重复创建相同的实例,节省资源。

为整个应用程序提供一个全局访问点,方便在不同地方使用同一个实例。

1.类创建个实例

2.然后用构造函数赋值给实例

3.其他地方调用时返回实例

c 复制代码
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;
  }
}

第二种方法:

c 复制代码
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 实例会被创建

相关推荐
Jiaberrr7 分钟前
Element UI教程:如何将Radio单选框的圆框改为方框
前端·javascript·vue.js·ui·elementui
安冬的码畜日常2 小时前
【D3.js in Action 3 精译_029】3.5 给 D3 条形图加注图表标签(上)
开发语言·前端·javascript·信息可视化·数据可视化·d3.js
太阳花ˉ2 小时前
html+css+js实现step进度条效果
javascript·css·html
john_hjy3 小时前
11. 异步编程
运维·服务器·javascript
早起的年轻人3 小时前
Flutter String 按 ,。分割
flutter
风清扬_jd3 小时前
Chromium 中JavaScript Fetch API接口c++代码实现(二)
javascript·c++·chrome
yanlele3 小时前
前瞻 - 盘点 ES2025 已经定稿的语法规范
前端·javascript·代码规范
It'sMyGo3 小时前
Javascript数组研究09_Array.prototype[Symbol.unscopables]
开发语言·javascript·原型模式
xgq4 小时前
使用File System Access API 直接读写本地文件
前端·javascript·面试