Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Design Pattern - How to write code based on highly configurable user selections

I would like to write code without a lot of switch, if/else, and other typical statements that would execute logic based on user input.

For example, lets say I have a Car class that I want to assemble and call Car.Run(). More importantly, lets say for the tires I have a chocie of 4 different Tire classes to choose from based on the user input.

For the, i dunno, body type, letS say i have 10 body type classes to choose from to construct my car object, and so on and so on.

What is the best pattern to use when this example is magnified by 1000, with the number of configurable parameters.

Is there even a pattern for this ? Ive looked at factory and abstract factory patterns, they dont quite fit the bill for this, although it would seem like it should.

like image 445
Shawn Avatar asked Dec 30 '22 10:12

Shawn


2 Answers

I don't think the factory pattern would be remiss here. This is how I would set it up. I don't see how you can get away from switch/if based logic as fundamentally, your user is making a choice.

public class Car {
   public Engine { get; set; }
   //more properties here
}

public class EngineFactory {
  public Engine CreateEngine(EngineType type {
     switch (type) {
        case Big:
           return new BigEngine();
        case Small:
           return new SmallEngine();
     }
  }   
}

public class Engine {

}

public class BigEngine : Engine {

}

public class SmallEngine : Engine {

}

public class CarCreator {
   public _engineFactory = new EngineFactory();
   //more factories

   public Car Create() {
    Car car = new Car();

    car.Engine = _engineFactory.CreateEngine(ddlEngineType.SelectedValue);
    //more setup to follow

    return car;
   }
}
like image 53
Richard Nienaber Avatar answered Jan 05 '23 14:01

Richard Nienaber


The problem you tell of can be solved using Dependency Injection.

There're many frameworks implementing this pattern (for example, for .NET - excellent Castle.Windsor container).

like image 29
elder_george Avatar answered Jan 05 '23 16:01

elder_george