Quick Index
Overview


Using static factory methods are generally preferred over traditional constructors.

They allow simpler and clearer related to constructing objects.

Java Static Factory Methods


Coding Public Static Factory Methods
Two static factory methods in class Rectangle.

Note, they are calling traditional constructors (as we'll discuss next).
//-----------------------------------------------------------------
//Static Factory Methods

public static Rectangle fromWidthHeight(int w, int h) {
	//Construct and return a basic rectangle
	return new Rectangle(10, 5);
}

public static Rectangle fromSide(int side) {
	//Construct and return a square
	//I.e., a rectangle with equal width and height
	return new Rectangle(side, side);
}

Private Traditional Constructors
We still use traditional constructor(s) to do the construction work. We want to to keep the actual construction logic on the instance side (where we can reference "this").

Note these are private.
private Rectangle(int w, int h)
{
	this.width = w;
	this.height = h;
}

private Rectangle() {
	this(0, 0);
}

Using Public Static Factory Methods
The construction is now explicit (e.g., we know we are passing one "side" into constructor) which improves code clarity.
Rectangle rec, square;

//Construct a basic rectangle
rec = Rectangle.fromWidthHeight(10, 5);
//10x5

//Construct a squuare
square = Rectangle.fromSide(8);
//8x8


JavaScript Static Factory Methods


Coding Public Static Factory Methods
Two static factory methods in class Rectangle.

Note, they are calling traditional constructors (as we'll discuss next).
//-----------------------------------------------------------------
//Static Factory Methods (Public)

static fromWidthHeight(w, h) {
	//Construct and return a basic rectangle
	return new Rectangle(10, 5);
}

static fromSide(side) {
	//Construct and return a square
	//I.e., a rectangle with equal width and height
	return new Rectangle(side, side);
}

Private Traditional Constructor
We still use traditional constructor(s) to do the construction work. We want to to keep the actual construction logic on the instance side (where we can reference "this").

Note these are private.
constructor(w, h) {
	//Use Nullish_coalescing_operator "??" (args are optional)
	//default is 0 for each
	this.w = w ?? 0;
	this.h = h ?? 0;
}

Using Public Static Factory Methods
The construction is now explicit (e.g., we know we are passing one "side" into constructor) which improves code clarity.
var rec, square;

//Construct a basic rectangle
rec = Rectangle.fromWidthHeight(10, 5);
//10x5

//Construct a squuare
square = Rectangle.fromSide(8);
//8x8



Navigation