does a factory just return an implementation of an interface? Is that the job?
Sometimes that's all a factory does, but they can also:
Choose a concrete implementation based on data that's only available at run-time:
// Beverage Factory
public IBeverage CreateBeverage(DateTime orderDate) {
return orderDate.Hour > 12 ? new Beer() : new Milk();
}
Perform post-construction initialization (often expensive initialization or initialization of data that's not appropriate to encapsulate within the object itself):
// Weather report factory
public IWeatherReport CreateWeatherReport() {
WeatherReport report = new WeatherReport();
report.data = WeatherWebService.GetData();
return report;
}
Initialize the new instance based on an existing instance:
// Fittest Algorithm Factory
public Algorithm CreateNewAlgorithm() {
return this.fittestAlgorithm.Clone();
}
Draw an instance from a pool instead of creating one from scratch:
public IDbConnection CreateConnection(string connectionString) {
return this.ConnectionStacks[connectionString].Pop();
}
Return a singleton instance (though yuck, and you'd better be sure it's thread safe!)
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