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.
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;
}
}
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With