Does factory just return an interface implementation?

Does factory return an interface implementation? This task?

+4
source share
5 answers

Sometimes this is all factory, but they can also:

  • Choose a specific implementation based on data available only at runtime:

    // Beverage Factory public IBeverage CreateBeverage(DateTime orderDate) { return orderDate.Hour > 12 ? new Beer() : new Milk(); } 
  • Perform initialization after construction (often expensive initialization or initialization of data that is not suitable for encapsulation inside the object itself):

     // Weather report factory public IWeatherReport CreateWeatherReport() { WeatherReport report = new WeatherReport(); report.data = WeatherWebService.GetData(); return report; } 
  • Initialize a new instance based on the existing instance:

     // Fittest Algorithm Factory public Algorithm CreateNewAlgorithm() { return this.fittestAlgorithm.Clone(); } 
  • Draw an instance from the pool instead of creating it from scratch:

     public IDbConnection CreateConnection(string connectionString) { return this.ConnectionStacks[connectionString].Pop(); } 
  • Bring back the singleton instance (although yuck, and you better be sure of the thread!)

+13
source

See wikipedia . Depending on what you mean by "returning the implementation of the interface", yes. But this definition may not be very accurate / comprehensive (especially since the Factory pattern does not necessarily require an interface concept).

+4
source

From the Wiki:

The essence of the Factory template is to “Define an interface for creating an object, but let the subclasses decide which class should instantiate. The Factory method allows the class to transfer the instance to subclasses.

+4
source

In fact, yes.

However, depending on your language, an “interface” may have a certain meaning. A factory usually returns a specific implementation of a general contract - which may be an interface, a base class, or any other means of specialization.

In addition, there are times when the factory returns the exact type that you specify, but you use the factory for other purposes, such as managing lifespan, tracking, or other justification, other than creating a specialized type.

+2
source

Share great resources with you:

A more specific answer is that Factory should provide pre-initialization and pre-operation for shared object types. The simplest example (I saw) of this is the “Hammer factory”, where the hammer is built from two objects (a pen and a head) and gets one name “a wood-worked hammer”. Therefore, our Factory can have one method:

 (Hammer|IHammer|...) GetHammer(string hammername); 

which can return one of several objects (the actual Hammer object, the interface describing Hammer, the base class for Hammer, etc.). Perhaps the most useful of these is to return the interface that the hammer describes and allows us to implement some useful design patterns there.

+2
source

All Articles