Factory methods

Factory methods are static methods that return an instance of the native class. Examples in the JDK: Factory methods: Common names for factory methods include getInstance and valueOf. These names are not mandatory - choose whatever makes sense for each case.


public final class ComplexNumber {

  * Static factory method returns an object of this class.
  public static ComplexNumber valueOf(float aReal, float aImaginary) {
    return new ComplexNumber(aReal, aImaginary);

  * Caller cannot see this private constructor.
  * The only way to build a ComplexNumber is by calling the static 
  * factory method.
  private ComplexNumber(float aReal, float aImaginary) {
    fReal = aReal;
    fImaginary = aImaginary;

  private float fReal;
  private float fImaginary;


See Also :
Immutable objects
Private constructor
Implementing toString
Data access objects
Avoid clone
Abstract Factory
Would you use this technique?
Yes   No   Undecided   
© 2015 Hirondelle Systems | Source Code | Contact | License | RSS
Individual code snippets can be used under this BSD license - Last updated on September 21, 2013.
Over 2,000,000 unique IPs last year - Built with WEB4J.
- In Memoriam : Bill Dirani -