I often find myself creating classes that I suffix with 'Factory'. These classes tend to be solely in charge of the creation of a specific class or set of related classes. However I've always felt that this probably isn't best practice and that there's a better way of approaching this. One of the reasons that I believe that this isn't best practice is down to the fact that although I am using the 'factory' suffix I am not actually making use of the factory design pattern.
Let's say I have an class vehicle
, that contains two variables make
and model
. I want my problem to be able to create a number of these vehicle objects, so I want to encapsulate the code to create these objects in a single class. I might create the below class.
public class VehicleFactory
{
public Vehicle CreateVehicle(string make, string model)
{
//create vehicle..
return vehicle;
}
}
The VehicleFactory
can then be used wherever I want in my program without repeating the code and violating DRY.
I often need to create these kind of factory classes when I'm refactoring code, more specifically when I find two or more classes that are creating the same objects. I'd want to refactor the code by pulling out the repeated code and then placing it inside a specific factory class.
Is there a better way to approach this issue?
CreateVehicle
work.