Factory Functions
Sticking with our airplane example, we've got:
const plane = new Airplane(); plane.type = PlaneType.Passenger; plane.engine = new PassengerPlaneEngine(); plane.hasFirstClass = true; plane.hasBathroom = false; plane.numberOfSeats = 100; // etc.
In another place within this airline application, you need to write some code that does the same thing except makes the numberOfSeats
variable a different value:
plane.numberOfSeats = 50;
Should we copy and paste all the code that creates a new airplane? Of course not!
Instead, we can create targeted functions that will deal with creating the airplane for us. These are called Factory Functions.
This will allow us to easily create a new airplane whenever we want and also gain the benefits of being able to configure how that plane is built:
const createPassengerPlane = (numberOfSeats: number): Airplane => { const plane = new Airplane(); plane.type = PlaneType.Passenger; plane.engine = new...