在 HarmonyOS 中,如果你希望单例在不同页面之间共享数据,可以通过全局状态管理、应用级别的单例模式或者存储机制来实现。


以下是一些常见的解决方案:


1. 使用全局状态管理

HarmonyOS 提供了 @State 和 @Link 修饰符,可以用于跨组件或页面共享数据。但当涉及到复杂的状态管理需求时,使用一个全局状态管理器(如 Vuex 或 Redux)会更加方便。


示例代码(简单全局状态管理)


// globalState.ts
export class GlobalState {
    private static instance: GlobalState;
    public data: any;

    private constructor() {
        this.data = {};
    }

    public static getInstance(): GlobalState {
        if (!GlobalState.instance) {
            GlobalState.instance = new GlobalState();
        }
        return GlobalState.instance;
    }
}

在你的页面中使用这个全局状态:


// PageA.ts
import { GlobalState } from './globalState';

@Component
struct PageA {
    build() {
        const globalState = GlobalState.getInstance();
        globalState.data.someKey = "someValue";

        // 页面构建逻辑
    }
}

// PageB.ts
import { GlobalState } from './globalState';

@Component
struct PageB {
    build() {
        const globalState = GlobalState.getInstance();
        console.log(globalState.data.someKey); // 输出 "someValue"

        // 页面构建逻辑
    }
}

2. 使用应用级别的单例模式

创建一个全局的单例对象并将其挂载到应用实例上,这样可以确保在不同页面间共享同一个实例。


示例代码


// appSingleton.ts
export class AppSingleton {
    private static instance: AppSingleton;
    public someProperty: string;

    private constructor() {
        this.someProperty = "";
    }

    public static getInstance(): AppSingleton {
        if (!AppSingleton.instance) {
            AppSingleton.instance = new AppSingleton();
        }
        return AppSingleton.instance;
    }
}

在应用入口文件中初始化单例:


// mainAbility.ts
import { AppSingleton } from './appSingleton';

@Entry
@Component
struct MainAbility {
    onInit() {
        const singleton = AppSingleton.getInstance();
        singleton.someProperty = "Initial Value";
    }

    build() {
        Column() {
            // 应用主页面内容
        }
    }
}

// PageA.ts
import { AppSingleton } from './appSingleton';

@Component
struct PageA {
    @State singletonProperty: string;

    onInit() {
        const singleton = AppSingleton.getInstance();
        this.singletonProperty = singleton.someProperty;
    }

    build() {
        Column() {
            Text(this.singletonProperty);

            Button("Update Singleton Property")
                .onClick(() => {
                    const singleton = AppSingleton.getInstance();
                    singleton.someProperty = "Updated Value";
                });
        }
    }
}

// PageB.ts
import { AppSingleton } from './appSingleton';

@Component
struct PageB {
    @State singletonProperty: string;

    onInit() {
        const singleton = AppSingleton.getInstance();
        this.singletonProperty = singleton.someProperty;
    }

    build() {
        Column() {
            Text(this.singletonProperty);
        }
    }
}

3. 使用本地存储

如果需要在应用关闭后仍然保留数据,可以使用 HarmonyOS 提供的本地存储 API,如 preferences。


示例代码


// storageHelper.ts
import preferences from '@ohos.data.preferences';

export async function saveData(key: string, value: string) {
    const prefs = await preferences.getPreferences('my_prefs');
    prefs.putString(key, value);
    await prefs.flush();
}

export async function loadData(key: string): Promise<string> {
    const prefs = await preferences.getPreferences('my_prefs');
    return prefs.getString(key, '');
}

在页面中使用存储操作:


// PageA.ts
import { saveData, loadData } from './storageHelper';

@Component
struct PageA {
    async onInit() {
        await saveData('someKey', 'someValue');
    }

    build() {
        Column() {
            Button("Save Data")
                .onClick(async () => {
                    await saveData('someKey', 'newValue');
                });
        }
    }
}

// PageB.ts
import { loadData } from './storageHelper';

@Component
struct PageB {
    @State storedValue: string = '';

    async onInit() {
        this.storedValue = await loadData('someKey');
    }

    build() {
        Column() {
            Text(this.storedValue);
        }
    }
}

总结

通过全局状态管理、应用级别的单例模式或本地存储,你可以在不同页面之间共享数据并保持单例的行为。选择合适的方法取决于你的具体需求和应用场景。