/// <summary> /// Проверка валидности состояния улья. /// </summary> /// <param name="state">Состояние улья.</param> public static void Validate(this IBeehiveState state) { if (state.BeesTotalCount != (state.WorkerBeesCount + state.QueensCount + state.GuardsCount)) { throw new ValidationException("Общее количество пчёл несовпадает с суммой количеств пчёл разных видов."); } if (state.BeesInsideCount < (state.QueensCount + state.GuardsCount)) { throw new ValidationException("Количество пчёл внутри улья подразумевает, что снаружи находятся не только рабочие пчёлы."); } if (state.BeesInsideCount > state.BeesTotalCount) { throw new ValidationException("Количество пчёл внутри улья больше, чем количество пчёл вообще."); } if (state.BeesInsideCount < 0 || state.BeesTotalCount < 0 || state.GuardsCount < 0 || state.QueensCount < 0 || state.WorkerBeesCount < 0 || state.BeehiveNumber < 0 || state.HoneyCount < 0) { throw new ValidationException("Ни одно из значений не может быть < 0."); } }
/// <summary> /// Инициализировать свойства для реализации интерфейса IBeehiveState. /// </summary> /// <param name="state">Состояние улья.</param> private void InitializeBeehiveStateProperties(IBeehiveState state) { this.BeehiveNumber = state.BeehiveNumber; this.GuardsCount = state.GuardsCount; this.QueensCount = state.QueensCount; this.WorkerBeesCount = state.WorkerBeesCount; this.BeesInsideCount = state.BeesInsideCount; this.HoneyCount = state.HoneyCount; }
/// <summary> /// Создать потокобезопасное изменяемое состояние улья. /// </summary> /// <param name="baseBeehiveState">Исходные данные состояния улья.</param> public BeehiveStateThreadSafe(IBeehiveState baseBeehiveState) { this.BeehiveNumber = baseBeehiveState.BeehiveNumber; this.honeyCount = baseBeehiveState.HoneyCount; this.beesInsideCount = baseBeehiveState.BeesInsideCount; this.workerBeesCount = baseBeehiveState.WorkerBeesCount; this.queensCount = baseBeehiveState.QueensCount; this.guardsCount = baseBeehiveState.GuardsCount; }
/// <summary> /// Создать улей, запустить его на 5 секунд, и остановить. /// </summary> /// <param name="initialState">Изначальное состояние улья.</param> /// <returns>Состояние отработавшего улья.</returns> private IBeehiveState LaunchBeehiveForFiveSeconds(IBeehiveState initialState) { BeeWorkflowBeehive beehive = new BeeWorkflowBeehive(); beehive.Start(initialState); Task.Delay(5000).GetAwaiter().GetResult(); IBeehiveState state = beehive.Stop(); state.Validate(); return(state); }
/// <summary> /// Создать улей, и запустить его, как будто он работал /// в течение часа. /// </summary> /// <param name="state">Состояние улья.</param> /// <param name="checkForEveryIteration">Проверка на каждой итерации.</param> /// <returns>Улей, отработавший час и остановленный.</returns> private MathBeehive CreateBeehiveWorkedForHour( IBeehiveState state, Action <MathBeehive> checkForEveryIteration = null) { MathBeehive beehive = new MathBeehive(state); for (int i = 0; i < this.GetIterationsInHour(beehive); i++) { checkForEveryIteration?.Invoke(beehive); beehive.SingleIteration(); } beehive.Validate(); return(beehive); }
public void BeeWorkflowBeehive_BeesCountStable() { IBeehiveState initialState = new BeehiveXmlState { HoneyCount = 0, BeesTotalCount = 10000, BeesInsideCount = 10000, WorkerBeesCount = 9000, QueensCount = 0, GuardsCount = 1000 }; IBeehiveState newState = this.LaunchBeehiveForFiveSeconds(initialState); Assert.AreEqual(initialState.BeesTotalCount, newState.BeesTotalCount); }
/// <summary> /// Создать улей, работающий на основе итерационных /// математических вычислений. /// </summary> /// <param name="state"></param> public MathBeehive( IBeehiveState state) { state.Validate(); IApiaryBalance balance = ServiceLocator.Instance.GetService <IApiaryBalance>(); this.InitializeBeehiveStateProperties(state); this.waitingForWork = state.BeesInsideCount - state.QueensCount - state.GuardsCount; this.waitingForCheck = state.WorkerBeesCount - waitingForWork; this.InitializeOperationTimes(balance); this.InitializeIntervals(); this.ValidateIntervals(); this.InitializeQueues(); this.InitializeQueueRatios(); }
/// <summary> /// "Запустить" улей. /// </summary> /// <param name="state">Исходное состояние улья.</param> public void Start(IBeehiveState state) { state.Validate(); if (this.isWorking) { throw new InvalidOperationException( "Улей нельзя запустить, если он уже работает."); } this.isWorking = true; this.allBees = new ConcurrentQueue <IBee>(); this.state = new BeehiveStateThreadSafe(state); this.guardPostQueue = new GuardPostQueue(); this.acceptedList = new GuardPostAcceptedList(); this.StartWork(); }
public void BeeWorkflowBeehive_CorrectGuardsLimitation() { IBeehiveState initialState = new BeehiveXmlState { HoneyCount = 0, BeesTotalCount = 10000, BeesInsideCount = 10000, WorkerBeesCount = 9900, QueensCount = 0, GuardsCount = 100 }; IBeehiveState newState = this.LaunchBeehiveForFiveSeconds(initialState); int expectedHoney = this.ChecksFromOneGuardPerFiveSeconds * initialState.GuardsCount; Assert.IsTrue(Math.Abs(expectedHoney - newState.HoneyCount) <= expectedHoney * BeeWorkflowBeehiveTests.Inaccuracy); }
public void BeeWorkflowBeehive_CorrectBeeProducing() { IBeehiveState initialState = new BeehiveXmlState { HoneyCount = 0, BeesTotalCount = 1000, BeesInsideCount = 1000, WorkerBeesCount = 0, QueensCount = 1000, GuardsCount = 0 }; IBeehiveState newState = this.LaunchBeehiveForFiveSeconds(initialState); int expectedNewBees = this.ChildrenFromOneQueenPerFiveSeconds * initialState.QueensCount; Assert.IsTrue(Math.Abs(expectedNewBees - newState.BeesTotalCount) <= expectedNewBees * BeeWorkflowBeehiveTests.Inaccuracy); }
public void BeeWorkflowBeehive_CorrectHoneyHarvesting() { IBeehiveState initialState = new BeehiveXmlState { HoneyCount = 0, BeesTotalCount = 5000, BeesInsideCount = 5000, WorkerBeesCount = 1000, QueensCount = 0, GuardsCount = 4000 }; IBeehiveState newState = this.LaunchBeehiveForFiveSeconds(initialState); int expectedHoney = this.HoneyPerFiveSecondsFromOneBee * initialState.WorkerBeesCount; Assert.IsTrue(Math.Abs(expectedHoney - newState.HoneyCount) <= expectedHoney * BeeWorkflowBeehiveTests.Inaccuracy); }
public void BeeWorkflowBeehive_OutsideWorkersNormalStartTheirWork() { IBeehiveState initialState = new BeehiveXmlState { HoneyCount = 500, BeesTotalCount = 1900, BeesInsideCount = 1000, WorkerBeesCount = 900, QueensCount = 0, GuardsCount = 1000 }; IBeehiveState newState = this.LaunchBeehiveForFiveSeconds(initialState); long expectedHoney = this.HoneyPerFiveSecondsFromOneBee * initialState.WorkerBeesCount + initialState.HoneyCount; Assert.IsTrue(Math.Abs(expectedHoney - newState.HoneyCount) <= expectedHoney * BeeWorkflowBeehiveTests.Inaccuracy); }
/// <summary> /// Создать модель представления улья. /// </summary> /// <param name="state">Состояние улья.</param> public BeehiveVM(IBeehiveState state) { this.state = state; Task.Factory.StartNew(PermanentChangePropertiesAsync); }