ex-int-05-numbers/Numbers/NumberFactory/AbstractNumbers.cs
2025-05-10 22:58:56 +02:00

67 lines
1.9 KiB
C#

using System.Collections;
namespace Numbers.NumberFactory;
/// <summary>
/// Base class for <see cref="INumbers" /> implementations
/// </summary>
/// <inheritdoc cref="INumbers" />
public abstract class AbstractNumbers : INumbers
{
private readonly List<long> _list;
/// <summary>
/// Creates a new instance of <see cref="AbstractNumbers" /> with the given bounds.
/// Will generate the appropriate numbers based on the implementation of <see cref="PickNumber" />.
/// </summary>
/// <param name="lowerBound">Lower bound of the number range</param>
/// <param name="upperBound">Upper bound of the number range</param>
protected AbstractNumbers(long lowerBound, long upperBound)
{
LowerBound = lowerBound;
UpperBound = upperBound;
_list = [];
GenerateNumbers();
}
public long this[int index]
{
get
{
if (index < 0 || index >= _list.Count)
{
return -1;
}
return _list[index];
}
}
public long LowerBound { get; }
public long UpperBound { get; }
public int Length => _list.Count;
public IEnumerator<long> GetEnumerator() => new NumbersEnumerator(_list);
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
private void GenerateNumbers()
{
for (var i = LowerBound; i <= UpperBound; i++)
{
if (PickNumber(i))
{
_list.Add(i);
}
}
}
/// <summary>
/// Determines whether the given number should be picked based on the task of a
/// specific <see cref="INumbers" /> implementation
/// </summary>
/// <param name="number">Number to check</param>
/// <returns>True if the number should be picked; false otherwise</returns>
protected abstract bool PickNumber(long number);
}