That is really not how you should be using a Stopwatch
...
E.g. this
while (Timer.Elapsed.TotalMilliseconds < Duration) { }
You're needlessly using CPU cycles while you're waiting. That's not good! You know exactly when you want to do something so you should scheduled something rather than do pretend work. A simple example could be:
private void ThreadMethod(IUnit unit)
{
Activate(unit);
Task.Delay(Duration).ContinueWith(_ => Deactivate(unit));
}
This isn't safe either:
while (Timer.ElapsedMilliseconds < Duration)
{
if (Timer.Elapsed.TotalMilliseconds % TickTime == 0)
ApplyTick(unit);
}
You're very unlikely to actually get true
on that if statment meaning you're unlikely to call ApplyTick and almost certainly won't call it the number of times you want to! That's because a Tick is a really, really small measure of time... I want to say 1/10000 of a millisecond.
You shouldn't need a stopwatch at all for this sort of thing.
You should use the highest level of abstraction you can. A double can be anything (e.g. hours, minutes, seconds...) - a timespan is a period of time, much more suitable for your LimitedTimeBehavior
:
public abstract class LimitedTimeBehavior : IBehavior
{
public abstract void ApplyBehavior(IUnit unit);
public TimeSpan Duration { get; }
protected LimitedTimeBehavior(TimeSpan duration)
{
Duration = duration;
}
}
You said you're interested in design patterns so I though I'd draw your attention to one you're nearly using:
public abstract class ActivatableBehavior : IBehavior
{
public abstract bool BehaviorImplentation(IUnit destinationPlayer);
public void ApplyBehavior(IUnit unit)
{
BehaviorImplentation(unit);
}
}
That's the Template Method pattern but it's more normal to call multiple methods within the template method.
public abstract class ActivatableBehavior : IBehavior
{
public abstract void BehaviorImplementation(IUnit destinationPlayer);
public abstract bool CanApplyBehvaiorTo(IUnit destinationPlayer);
public void ApplyBehavior(IUnit unit)
{
if (CanApplyBehvaiorTo(unit))
{
BehaviorImplementation(unit);
}
}
}
Note that I've fixed your typo (Implentation -> Implementation) and have removed the bool
return type that was never used.