Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

does a factory just return an implementation of an interface?

does a factory just return an implementation of an interface? Is that the job?

like image 568
mrblah Avatar asked Nov 28 '22 23:11

mrblah


1 Answers

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!)

like image 155
Jeff Sternal Avatar answered Dec 23 '22 22:12

Jeff Sternal