I'm making a problem solving program which takes as an input an ID which I later use to locate the problem in my list of problems.
I have the following hierarchy
Base class for all problems
public abstract class Problem
{
public abstract int ID { get; }
protected Problem()
{
Controller.Problems.Add(this);
}
public abstract ProblemOutput Solve();
}
Derived class Problem01
public sealed class Problem01 : Problem
{
public override int ID => 1;
private ProblemOutput problemOutput;
public override ProblemOutput Solve()
{
//solving the problem here
}
}
And this is where I run the main code
internal static List<Problem> Problems = new List<Problem>();
static void Main(string[] args)
{
Console.Write("Enter problem number");
int problemNumber;
while (!int.TryParse(Console.ReadLine(), out problemNumber))
{
Console.Write("Invalid input");
}
if (Problems.All(p => p.ID != problemNumber))
{
Console.WriteLine("Sorry this problem is not solved yet");
}
else
{
ProblemOutput problemOutput = Problems.Single(p => p.ID == problemNumber).Solve();
Console.WriteLine(problemOutput.OutputText);
Console.WriteLine();
Console.WriteLine($@"Time took to calculate in milliseconds : {problemOutput.TimeToSolve}");
}
}
But there's a problem with this since Problem01 is never being instantiated the base constructor wont be triggered thus not getting added into the list but in the same time I never need to instantiate the class itself I just need to use the solve method from the respective 'Problem' class. Is there any design pattern or some better solution that I can apply here ?
Aucun commentaire:
Enregistrer un commentaire