Skip to content

Commit

Permalink
add singleton wrap
Browse files Browse the repository at this point in the history
  • Loading branch information
Forairaaaaa committed Sep 30, 2024
1 parent 13711cf commit cd271f2
Show file tree
Hide file tree
Showing 5 changed files with 76 additions and 0 deletions.
1 change: 1 addition & 0 deletions cmake/basic.cmake
Original file line number Diff line number Diff line change
Expand Up @@ -36,3 +36,4 @@ enable_testing()
add_test(basic_demo example/basic_demo)
add_test(ability_manager_test example/ability_manager_test)
add_test(extension_test example/extension_test)
add_test(singleton_test example/singleton_test)
3 changes: 3 additions & 0 deletions example/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -15,3 +15,6 @@ target_link_libraries(ui_ability_test ${PROJECT_NAME})

add_executable(app_ability_test ./app_ability_test.cpp)
target_link_libraries(app_ability_test ${PROJECT_NAME})

add_executable(singleton_test ./singleton_test.cpp)
target_link_libraries(singleton_test ${PROJECT_NAME})
24 changes: 24 additions & 0 deletions example/singleton_test.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
/**
* @file singleton_test.cpp
* @author Forairaaaaa
* @brief
* @version 0.1
* @date 2024-09-30
*
* @copyright Copyright (c) 2024
*
*/
#include <cstdio>
#include <mooncake.h>

using namespace mooncake;

int main()
{
printf("app name: %zu\n", GetMooncake().getAppNum());

DestroyMooncake();
GetMooncake();

return 0;
}
30 changes: 30 additions & 0 deletions src/mooncake.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -165,3 +165,33 @@ void Mooncake::resetExtensionManager()
{
_extension_ability_manager.reset();
}

/* -------------------------------------------------------------------------- */
/* Singleton */
/* -------------------------------------------------------------------------- */
// 懒加载单例

static std::unique_ptr<Mooncake> _mooncake_instance;

/**
* @brief 获取 Mooncake 单例
*
* @return Mooncake&
*/
Mooncake& mooncake::GetMooncake()
{
if (!_mooncake_instance) {
_mooncake_instance = std::make_unique<Mooncake>();
_mooncake_instance->logAboutMsg();
}
return *_mooncake_instance;
}

/**
* @brief 销毁 Mooncake 单例
*
*/
void mooncake::DestroyMooncake()
{
_mooncake_instance.reset();
}
18 changes: 18 additions & 0 deletions src/mooncake.h
Original file line number Diff line number Diff line change
Expand Up @@ -150,4 +150,22 @@ class Mooncake {
AbilityManager* get_extension_ability_manager();
};

/* -------------------------------------------------------------------------- */
/* Singleton */
/* -------------------------------------------------------------------------- */
// 全局单例

/**
* @brief 获取 Mooncake 单例
*
* @return Mooncake&
*/
Mooncake& GetMooncake();

/**
* @brief 销毁 Mooncake 单例
*
*/
void DestroyMooncake();

} // namespace mooncake

0 comments on commit cd271f2

Please sign in to comment.