目录
创建状态具体类:UBaseStateWidget,作为UI的父类
描述
允许一个对象在其内部状态改变时改变它的行为,对象看起来似乎修改了它的类
其别名为状态对象,状态模式是一种对象行为型模式

并发状态机
层次状态机
下推自动机
切换UI模式
- UINTERFACE(MinimalAPI)
- class UStateInterface : public UInterface
- {
- GENERATED_BODY()
- };
-
- /**
- *
- */
- class DESIGNPATTERNS_API IStateInterface
- {
- GENERATED_BODY()
-
- // Add interface functions to this class. This is the class that will be inherited to implement this interface.
- public:
- virtual void EnterState() = 0;
- virtual void ExitState() = 0;
- };
- UCLASS()
- class DESIGNPATTERNS_API UBaseStateWidget : public UUserWidget, public IStateInterface
- {
- GENERATED_BODY()
- public:
- virtual void EnterState() override;
- virtual void ExitState() override;
-
- UFUNCTION(BlueprintNativeEvent,BlueprintCallable,Category="State Pattern")
- void OnEnterState();
- UFUNCTION(BlueprintNativeEvent, BlueprintCallable, Category = "State Pattern")
- void OnExitState();
- };
- void UBaseStateWidget::EnterState()
- {
- OnEnterState();
- }
-
- void UBaseStateWidget::ExitState()
- {
- OnExitState();
- }
-
- void UBaseStateWidget::OnEnterState_Implementation()
- {
- AddToViewport();
- }
-
- void UBaseStateWidget::OnExitState_Implementation()
- {
- RemoveFromParent();
- }
- UCLASS()
- class DESIGNPATTERNS_API AUIStateManager : public AActor
- {
- GENERATED_BODY()
-
- public:
- // Sets default values for this actor's properties
- AUIStateManager();
-
- protected:
- // Called when the game starts or when spawned
- virtual void BeginPlay() override;
-
- public:
- // Called every frame
- virtual void Tick(float DeltaTime) override;
-
- // 改变状态
- UFUNCTION(BlueprintCallable, Category = "State Pattern")
- void EnterState(TSubclassOf
StateWidgetClass) ; -
- // 退出所有状态
- UFUNCTION(BlueprintCallable, Category = "State Pattern")
- void ExitAllState();
-
- // 当前状态实例
- UPROPERTY(BlueprintReadWrite, Category = "State Pattern")
- UBaseStateWidget* CurrentStateWidget;
-
- private:
- // 存储状态实例
- TMap
, UBaseStateWidget*> WidgetInstances; - };
- void AUIStateManager::EnterState(TSubclassOf
StateWidgetClass) - {
- if (CurrentStateWidget != nullptr)
- {
- CurrentStateWidget->ExitState();
- }
-
- if (WidgetInstances.Contains(StateWidgetClass))
- {
- CurrentStateWidget = WidgetInstances.FindRef(StateWidgetClass);
- }
- else
- {
- APlayerController* PC = UGameplayStatics::GetPlayerController(GetWorld(), 0);
- CurrentStateWidget = CreateWidget
(PC, StateWidgetClass); - WidgetInstances.Add(StateWidgetClass,CurrentStateWidget);
- }
- CurrentStateWidget->EnterState();
- }
-
- void AUIStateManager::ExitAllState()
- {
- for (auto& Elem : WidgetInstances)
- {
- (Elem.Value)->ExitState();
- }
- }
4. 状态模式 — Graphic Design Patterns (design-patterns.readthedocs.io)