• UE4 设计模式:单例模式(Singleton Pattern)


    目录

    描述

    套路

    使用场景

    优缺点

    UE4中的单例模式

    GameInstance

    SubSystem

    自定义Singleton Class

    Game Singleton Class指定


    描述

    • 保证一个类只有一个实例
    • 提供一个访问该实例的全局节点,可以视为一个全局变量
    • 仅在首次请求单例对象时对其进行初始化

    套路

    • 将默认构造函数设为私有,防止其他对象使用单例类的new运算符
    • 新建一个静态构建方法作为构造函数

    使用场景

    • 资源Manager,如SoundManager、ParticleManager
    • 线程池
    • 多线程的单例模式,线程锁与双重检测

    优缺点

    • 优点
      • 提供了对唯一实例的受控访问
      • 由于内存只存在一个对象,因此可节约资源
      • 单例模式可以允许可变的数目的实例,使用单例模式进行扩展,使用控制单例对象相似的方法获取指定个数的实例,解决单例对象共享过多从而有损性能的问题
    • 缺点
      • 由于单例模式不是抽象的,所以可扩展性比较差
      • 单例职责过重,在一定程度上违背了单一职责(耦合性高)

    UE4中的单例模式

    GameInstance

    • 继承GameInstance创建类
    • Project Settings->Project->Game Instance -> Game Instance Class 设置为自定义类

    SubSystem

    自定义Singleton Class

    1. UCLASS(BlueprintType,Blueprintable)
    2. class DESIGNPATTERNS_API USingletonObject:public UObject{
    3. GENERATED_BODY()
    4. public:
    5. UFUNCTION(BlueprintCallable)
    6. static USingletonObject* GetSinletonObjectIns();
    7. UFUNCTION(BlueprintCallable)
    8. void SetValue(int32 NewValue);
    9. UFUNCTION(BlueprintCallable)
    10. int32 GetValue();
    11. private:
    12. static USingletonObject* SingletonObject;
    13. int32 IntValue;
    14. };
    15. USingletonObject* USingletonObject::SingletonObject=nullptr;
    16. USingletonObject* USingletonObject::GetSinletonObjectIns(){
    17. if(SingletonObject==nullptr){
    18. SingletonObject=NewObject();
    19. }
    20. return SinletonObject;
    21. }
    22. void USingletonObject::SetValue(int32 NewValue)
    23. {
    24. IntValue = NewValue;
    25. }
    26. int32 USingletonObject::GetValue()
    27. {
    28. UE_LOG(LogTemp, Warning, TEXT(__FUNCTION__" Value = %d"), IntValue);
    29. return IntValue;
    30. }

    Game Singleton Class指定

    • 继承 UObject 创建单例

    • Project Settings->Engine->General settings->Game Singleton Class 设置为自定义的单例类。会自动生成与销毁

    • 把它当成全局常量来用,不建议运行中修改其中的变量数据

    单例类代码,修改

    1. USingletonObject* USingletonObject::GetSingletonObjectIns()
    2. {
    3. if (SingletonObject == nullptr) // 也可以判断 GEngine
    4. {
    5. SingletonObject = Cast(GEngine->GameSingleton);
    6. }
    7. return SingletonObject;
    8. }

     UE4 C++ 笔记(二):基础知识_老闫在努力的博客-CSDN博客_ue4

  • 相关阅读:
    学习pytorch14 损失函数与反向传播
    后端编译与优化(JIT,即时编译器)
    「设计模式」六大原则之开闭职责小结
    无胁科技-TVD每日漏洞情报-2022-8-4
    git上传代码冲突
    为什么不直接操作State,而是要额外定义一个变量
    HQChart实战教程66-动态调整HQChart布局大小
    partial的使用,对定制化的想法
    竞价推广流程
    Stream根据多个字段去重
  • 原文地址:https://blog.csdn.net/Jason6620/article/details/126531204