饿汉式单例

类加载时直接初始化实例,且不可修改。线程安全、无需同步逻辑
缺点:相比 getInstance,类加载就初始化了,适合轻量级

LogStatistic.ets

export class LogStatistic extends BaseLogStatistic {

  private static readonly instance = new LogStatistic();

  // 静态方法获取实例(简化:直接返回预初始化的 instance)
  public static getInstance(): LogStatistic {
    return LogStatistic.instance; // 无需判断,直接返回
  }

  // 构造函数:添加私有构造器(关键),严格单例
  private constructor() {
    super()
    SLSLog.info("LogService 实例初始化(模块化单例)");
  }
}


// 导出实例(默认导出,方便外部直接导入)
export default LogStatistic.getInstance();

Index.ets

// 此处的作用是简化外部的导入
// 转发默认导出(核心实例)
export { default } from './src/main/ets/LogStatistic';

外部使用

import logService from 'xxx';

{
 logService.init(config)
}

标准单例

export class LogStatistic extends BaseLogStatistic {
private static readonly instancePool = new Map<string, LogStatistic>();

  public static getInstance(tag: string): LogStatistic {
    // 校验tag合法性(避免空key、undefined等异常)
    if (!tag?.trim()) {
      throw new Error("tag不能为空,请传入有效的标识(如渠道号、模块名)");
    }
    const validTag = tag.trim();

    // 检查实例池:有则返回,无则创建新实例
    if (!LogStatistic.instancePool.has(validTag)) {
      // 私有构造器只能在类内部调用,确保实例创建唯一入口
      LogStatistic.instancePool.set(validTag, new LogStatistic(validTag)); // 存入实例池
      SLSLog.info(`LogService 实例初始化(tag: ${validTag})`);
    }

    // 4. 强制类型断言:确保返回非undefined(因has()已判断,必然存在)
    return LogStatistic.instancePool.get(validTag)!;
  }

  // 构造函数:添加私有构造器(关键),严格单例
  // 3. 私有构造器:禁止外部new,确保实例只能通过getInstance创建
  private constructor(tag: string) {
    super(tag);
  }
}


// 导出类本身(关键:让外部能调用getInstance(tag))
export default LogStatistic;

全局单例

优点:简单

缺点:污染全局,只能存在一个同名实例

public static getInstance(): LogStatistic {
    if (globalThis.logstatistic== null) {
      globalThis.logstatistic = new LogStatistic();
    }
    return globalThis.logstatistic;
  }

Logo

讨论HarmonyOS开发技术,专注于API与组件、DevEco Studio、测试、元服务和应用上架分发等。

更多推荐