Quick Index
One Class - Many Objects


The one class or object type.

The class is like a blueprint or mold.

Construction Steps


The construction steps are basically:


Select The Object Type

First we select the object type that we'll construct. We're going with a "Ball" type.

At this starting point, the ball is just an idea (not real).

It is a definition variables "r" and "color".

We'll use this definition it to construct real balls.


Construct New Object

Use the Ball "definition" to construct a real "new object".


Initialize Object Values

Now "puff" the object up with real values (like r=10 and color=green) to make it a "real" object.


Construct two more ball objects from the "Ball" type definition:

  • The first with r=6 and color=orange
  • The second with r=3 and color=blue
Construct Many


We can construct an infinite number of objects from the "Ball" type definition.

Left: Our general type.

Right: Five objects all constructed from the one general type.

---------

%%3%%


Static Factory Constructors


A static factory constructor, in class X, is simply a static method that returns an instance of X.

Examples:

fromWidthHeight
This is a static factory method in class Rectangle. As we can see, it returns a Rectangle instance.
static fromWidthHeight(w, h) {
	//return a rectangle with dimensions w by h
	let rec = new Rectangle();
	rec.setWidth(w);
	rec.setHeight(h);
	return rec;
}
fromSide
Another static factory method.

This one returns a Rectangle instance that is a square with side length per the method param.
static fromSide(side) {
	//return a square per the param
	return this.fromWidthHeight(side, side);
}
Using Static Factory Methods
These methods make construction user-friendly, as shown.
let rec = Rectangle.fromWidthHeight(10, 5);
let square = Rectangle.fromSide(100);



Navigation