55 lines
1.9 KiB
C#
55 lines
1.9 KiB
C#
using System;
|
||
using Cysharp.Threading.Tasks;
|
||
|
||
namespace SLSUtilities.General
|
||
{
|
||
/// <summary>
|
||
/// 命令基类。子类重写 <see cref="ExecuteAsync"/> 实现具体逻辑。
|
||
/// 框架通过 <see cref="RunAsync"/> 调用,先处理可选延迟再执行核心逻辑。
|
||
/// </summary>
|
||
public abstract class CommandBase
|
||
{
|
||
/// <summary>命令自身的私有上下文,可携带局部参数。</summary>
|
||
public CommandContext selfContext;
|
||
|
||
private float delayBeforeExecute;
|
||
|
||
public CommandBase(CommandContext selfContext = null)
|
||
{
|
||
this.selfContext = selfContext ?? new CommandContext();
|
||
}
|
||
|
||
/// <summary>设置命令执行前的延迟秒数,返回自身支持链式调用。</summary>
|
||
public CommandBase SetDelay(float seconds)
|
||
{
|
||
delayBeforeExecute = seconds;
|
||
return this;
|
||
}
|
||
|
||
/// <summary>
|
||
/// 框架调用入口:先执行可选延迟,再调用 <see cref="ExecuteAsync"/>。
|
||
/// 子类不应重写此方法。
|
||
/// </summary>
|
||
public async UniTask RunAsync(CommandContext outerContext)
|
||
{
|
||
if (delayBeforeExecute > 0f)
|
||
await UniTask.Delay(TimeSpan.FromSeconds(delayBeforeExecute));
|
||
|
||
await ExecuteAsync(outerContext);
|
||
}
|
||
|
||
/// <summary>子类重写此方法以实现命令的核心逻辑。</summary>
|
||
protected virtual async UniTask ExecuteAsync(CommandContext outerContext)
|
||
{
|
||
await UniTask.CompletedTask;
|
||
}
|
||
|
||
/// <summary>浅拷贝当前命令,selfContext 也会被拷贝一份新实例。</summary>
|
||
public virtual CommandBase Clone()
|
||
{
|
||
CommandBase clone = (CommandBase)MemberwiseClone();
|
||
clone.selfContext = selfContext.Clone();
|
||
return clone;
|
||
}
|
||
}
|
||
} |