Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>While the example you provide is technically a factory method, it isn't very useful. Design patterns are only beneficial insofar as they can simplify development of the target application/feature. </p> <p>Generally, the benefit of a factory method implementation comes from:</p> <ol> <li>Standardizing the creation logic for objects</li> <li>Providing a semantically meaningful interface for object construction</li> </ol> <p>It's unclear how an instance method that takes no parameters would possibly add benefit over a default constructor.</p> <p>Take a look at the <a href="http://en.wikipedia.org/wiki/Factory_method_pattern#C.23" rel="nofollow">C# example from the Wikipedia Factory Method article</a>. (copied + pasted below)</p> <pre><code>public class Complex { public double real; public double imaginary; public static Complex FromCartesianFactory(double real, double imaginary) { return new Complex(real, imaginary); } public static Complex FromPolarFactory(double modulus, double angle) { return new Complex(modulus * Math.Cos(angle), modulus * Math.Sin(angle)); } private Complex(double real, double imaginary) { this.real = real; this.imaginary = imaginary; } } Complex product = Complex.FromPolarFactory(1, Math.PI); </code></pre> <p>It is useful, because it specifies two factory methods, each with clearly defined parameters and a clearly defined interpretation of how those parameters would be used to construct a valid instance of a well-defined object. In addition, the constructor is <code>private</code> and the factory method is <code>static</code>, which ensures that the only means of constructing an instance of that object is to use the factory method. While it doesn't apply to this example particularly (because all possible <code>double</code> parameter values are valid), it would make sense to put validation logic in the factory method or constructor as well. </p> <p>In general, <strong>the purpose of a factory method is to reduce code complexity by encapsulating object construction</strong> and it is unclear how the example you provided would accomplish that objective.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload