Question

I have a program I'm writing that has a form with around 15 inputs that describe a type of machine that we make (model, length, width, height, motor type, color, etc). There are 12 different models of this machine so I have a sub class "machine" and then 12 separate classes that inherit the "machine class". In my form, one of the inputs the user selects is the model. I'm trying to figure out a way to pass the 15 items to the specific "model" class fields without having to type it out 12 times with a case/switch (based on which model is selected). Is there a way to pass the inputs to the parent class and then when you figure out which specific class you need to create, reference the data that was stored in the parent class? I hope that makes sense what I'm saying. I'm struggling with describing the situation. If I can provide any more info please let me know!!

Thanks!

Was it helpful?

Solution

I would suggest you to write an interface, let's say something like IMachineModel with the required methods/properties. Write as many classes as models you have and implement the previously created interface.

Provide in each concrete class the logic required. Then you only need to instantiate the suitable class and use its properties and methods implemented from the interface.

Quick Example:

public class FirstConcreteMachineModel : IMachineModel
{
    public string Model { get; set; }

    public void DoSomething()
    {
        Console.WriteLine("I am a machine of type 1");
    }
}

public class SecondConcreteMachineModel : IMachineModel
{
    public string Model { get; set; }

    public void DoSomething()
    {
        Console.WriteLine("I am a machine of type 2");
    }
}

public class MachineModelFactory
{
    public static IMachineModel CreateMachineModel(string type)
    {
        //switch with all possible types
        switch (type)
        {
            case "one":
                return new FirstConcreteMachineModel { Model = type };

            case "two":
                return new SecondConcreteMachineModel { Model = type };

            default:
                throw new ArgumentException("Machine type not supported");
        }

    }
}

Then you can use it like:

IMachineModel machine = MachineModelFactory.CreateMachineModel("two");
machine.DoSomething();

It would print

I am a machine of type 2.

OTHER TIPS

To add to Areks's answer -- you could create a factory that given the inputs returns a class that implements IMachineModel .... Internally you have a number of options of how to determine the concrete class including your switch statement or chain of responsibility

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top