105 lines
2.5 KiB
C#
105 lines
2.5 KiB
C#
using System;
|
|
|
|
namespace Engine.Core;
|
|
|
|
public abstract class BaseEntity : IEntity
|
|
{
|
|
public Event<IIdentifiable, IIdentifiable.IdChangedArguments> OnIdChanged { get; } = new();
|
|
public Event<IInitializable> OnInitialized { get; } = new();
|
|
public Event<IInitializable> OnFinalized { get; } = new();
|
|
public Event<IHasStateEnable> OnStateEnableAssigned { get; } = new();
|
|
public Event<IAssignable> OnUnassigned { get; } = new();
|
|
|
|
public virtual IStateEnable StateEnable { get; private set; } = null!;
|
|
|
|
public string Id
|
|
{
|
|
get;
|
|
set
|
|
{
|
|
if (IsInitialized)
|
|
throw new($"Can't change {nameof(Id)} of {field} because it's initialized");
|
|
|
|
if (value == field)
|
|
return;
|
|
|
|
string previousId = field;
|
|
|
|
field = value;
|
|
OnIdChanged?.Invoke(this, new(previousId));
|
|
}
|
|
} = string.Empty;
|
|
|
|
public bool IsInitialized
|
|
{
|
|
get;
|
|
private set
|
|
{
|
|
if (value == field)
|
|
return;
|
|
|
|
field = value;
|
|
if (value)
|
|
OnInitialized?.Invoke(this);
|
|
else
|
|
OnFinalized?.Invoke(this);
|
|
}
|
|
} = false;
|
|
|
|
protected virtual void OnAssign(IStateEnable stateEnable) { }
|
|
public bool Assign(IStateEnable stateEnable)
|
|
{
|
|
if (IsInitialized)
|
|
return false;
|
|
|
|
StateEnable = stateEnable;
|
|
StateEnable.Assign(this);
|
|
OnAssign(stateEnable);
|
|
OnStateEnableAssigned?.Invoke(this);
|
|
return true;
|
|
}
|
|
|
|
protected virtual void UnassignInternal() { }
|
|
public bool Unassign()
|
|
{
|
|
if (IsInitialized)
|
|
return false;
|
|
|
|
UnassignInternal();
|
|
|
|
StateEnable = null!;
|
|
StateEnable.Unassign();
|
|
OnUnassigned?.Invoke(this);
|
|
return true;
|
|
}
|
|
|
|
protected virtual void InitializeInternal() { }
|
|
public bool Initialize()
|
|
{
|
|
if (IsInitialized)
|
|
return false;
|
|
|
|
StateEnable ??= Factory.StateEnableFactory.Instantiate(this);
|
|
|
|
InitializeInternal();
|
|
|
|
IsInitialized = true;
|
|
return true;
|
|
}
|
|
|
|
protected virtual void FinalizeInternal() { }
|
|
public bool Finalize()
|
|
{
|
|
if (!IsInitialized)
|
|
return false;
|
|
|
|
FinalizeInternal();
|
|
|
|
IsInitialized = false;
|
|
return true;
|
|
}
|
|
|
|
protected BaseEntity() => Id = Guid.NewGuid().ToString("D");
|
|
protected BaseEntity(string id) => Id = id;
|
|
}
|