Chapter 3. Creational Design Patterns

Creational design patterns in object-oriented programming are design patterns that are to be applied during the instantiation of objects. In this chapter, we'll be talking about patterns in this category.

Consider we are building a rocket, which has payload and one or more stages:

class Payload { 
  weight: number; 
} 
 
class Engine { 
  thrust: number; 
} 
 
class Stage { 
  engines: Engine[]; 
} 

In old-fashioned JavaScript, there are two major approaches to building such a rocket:

  • Constructor with new operator
  • Factory function

For the first approach, things could be like this:

function Rocket() { 
  this.payload = { 
    name: 'cargo ship' 
  }; 
   
  this.stages = [ 
    { 
      engines: [ 
        // ... 
      ] 
    } 
  ]; 
} 
 
var rocket = new Rocket(); 

And for the second approach, ...

Get TypeScript Design Patterns now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.