What is a Static Factory Method: Simply a static method that returns an instant of the class.
Advantages:
- Unlike constructors they have names.
- Different signatures.
- Unlike constructors, they are not required to make a new Object every time they are invoked.
- Unlike constructors, they can return an object of any subtype of their return type.
Disadvantages:
- Only disadvantage of providing static factory methods is that classes without public or protected constructors cannot be subclassed.
- They are not readily distinguishable from other static methods.
Example:
private CoordinatesStaticFactoryMethod(double x, double y) {
this.x = x;
this.y = y;
}
public static final CoordinatesStaticFactoryMethod fromXY(double x, double y) {
return new CoordinatesStaticFactoryMethod(x, y);
}
public static final CoordinatesStaticFactoryMethod fromAngles(double angle, double distance) {
return new CoordinatesStaticFactoryMethod(distance * Math.cos(angle), distance * Math.sin(angle));
}