DEV Community

HarmonyOS
HarmonyOS

Posted on

Singleton Pattern in ArkTS, Eager vs. Lazy Initialization Explained

Read the original article:Singleton Pattern in ArkTS, Eager vs. Lazy Initialization Explained

AI Generated Image

A comprehensive guide to implementing Singleton patterns in ArkTS, focusing on Eager and Lazy initialization strategies.

Introduction

In ArkTS development, managing shared services like loggers or analytics handlers efficiently is crucial. The Singleton design pattern ensures a class has only one instance, providing a global point of access. However, the timing of instance creation Eager vs. Lazy initialization can significantly impact application performance and resource utilization.

Understanding Singleton Initialization Strategies

Eager Initialization

In Eager initialization, the Singleton instance is created at the time of class loading

Pros:

  • Simple to implement.

  • Thread-safe without synchronization.
    Cons:

  • Instance is created even if not used, potentially wasting resources.
    Use Case: Services that are always required, like application wide logging

Lazy Initialization

Lazy initialization delays the creation of the Singleton instance until it is first needed

Pros:

  • Efficient resource utilization.

  • An instance is created only when required.
    Cons:

  • Requires synchronization in multithreaded environments.

  • Slight overhead on first access.
    Use Case: Services that are resource-intensive or not always needed, like complex caching mechanisms.

Implementing Singleton in ArkTS

Eager Singleton Example

export class LogManager {
private static readonly instance: LogManager = new LogManager();
private constructor() {}

static getInstance(): LogManager {
return this.instance;
}

info(tag: string, message: string): void {
console.log([INFO] [${tag}] ${message});
}
}

Usage
LogManager.getInstance().info('App', 'Started with eager singleton');

Lazy Singleton Example

export class LogManager {
private static instance: LogManager | null = null;
private constructor() {}

static getInstance(): LogManager {
if (!this.instance) {
this.instance = new LogManager();
}
return this.instance;
}

info(tag: string, message: string): void {
console.log([INFO] [${tag}] ${message});
}
}
Usage
LogManager.getInstance().info('Startup', 'Lazy singleton initialized');

Conclusion

Choosing between Eager and Lazy initialization in ArkTS depends on the specific needs of your application. Eager initialization is straightforward and suitable for services that are always required, while Lazy initialization conserves resources by creating instances only when needed. Understanding these strategies ensures efficient and effective Singleton implementations in your ArkTS projects.

References

(https://developer.huawei.com/consumer/en/doc/harmonyos-guides/arkts)

Written by Arif Emre Ankara

Top comments (0)