标签:ntc tcp gif 增加 default one 客户 stat ddt
允许一个对象在其内部状态改变时改变它的行为,对象看起来似乎修改了它的类。
其别名为状态对象(Objects for States),状态模式是一种对象行为型模式。
有限状态机(FSMs)
并发状态机
层次状态机
下推自动机
在UE4中,实现切换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;
};
创建状态具体类UBaseStateWidget ,作为UI的父类,切换时使用
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();
};
#include "BaseStateWidget.h"
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<UBaseStateWidget> StateWidgetClass);
// 退出所有状态
UFUNCTION(BlueprintCallable, Category = "State Pattern")
void ExitAllState();
// 当前状态实例
UPROPERTY(BlueprintReadWrite, Category = "State Pattern")
UBaseStateWidget* CurrentStateWidget;
private:
// 存储状态实例
TMap<TSubclassOf<UBaseStateWidget>, UBaseStateWidget*> WidgetInstances;
};
void AUIStateManager::EnterState(TSubclassOf<UBaseStateWidget> StateWidgetClass)
{
if (CurrentStateWidget != nullptr)
{
CurrentStateWidget->ExitState();
}
if (WidgetInstances.Contains(StateWidgetClass))
{
CurrentStateWidget = WidgetInstances.FindRef(StateWidgetClass);
}
else
{
APlayerController* PC = UGameplayStatics::GetPlayerController(GetWorld(), 0);
CurrentStateWidget = CreateWidget<UBaseStateWidget>(PC, StateWidgetClass);
WidgetInstances.Add(StateWidgetClass,CurrentStateWidget);
}
CurrentStateWidget->EnterState();
}
void AUIStateManager::ExitAllState()
{
for (auto& Elem : WidgetInstances)
{
(Elem.Value)->ExitState();
}
}
创建状态类UBaseStateWidget 的蓝图派生类
创建 UIStateManager 蓝图派生类
效果
扩展,可进一步用栈状态机实现界面管理
标签:ntc tcp gif 增加 default one 客户 stat ddt
原文地址:https://www.cnblogs.com/shiroe/p/14883132.html