Algobook
- The developer's handbook
mode-switch
back-button
Buy Me A Coffee
Sun Mar 19 2023

Factory pattern in TypeScript

The factory pattern is a design pattern which is used to create objects using factory methods without having to specify the exact class of the object being created.

What does that mean?

All right, so let say we have a class called phone, and we have sub classes like Iphone, HTC and Samsung, we want to, in a simply manner, create a Phone object without actually bother about which type it is. Using factory design pattern, this could be solved by a PhoneFactory class.

Let's implement it in TypeScript

We start with creating our abstract class
export abstract class Phone { price: number; diskSizeGb: number; constructor(price: number, diskSize: number) { this.price = price; this.diskSizeGb = diskSize; } abstract call(): void; }
Now we create our sub classes
export class Samsung extends Phone { androidVersion: string; constructor(price: number, diskSizeGb: number, androidVersion: string) { super(price, diskSizeGb); this.androidVersion = androidVersion; } call(): void { console.log('Calling with my Samsung') } } export class IPhone extends Phone { iOSVersion: string; constructor(price: number, diskSizeGb: number, iOSVersion: string) { super(price, diskSizeGb); this.iOSVersion = iOSVersion; } call(): void { console.log('Calling with my IPhone') } }
And now we create our Factory class
export class PhoneFactory { static create(type: string): Phone { if (type === 'Samsung') { return new Samsung(200, 64, 'Lollipop'); } else if (type === 'IPhone') { return new IPhone(200, 128, '16.3.1') } throw new Error('Not supported'); } }

So, now we have a PhoneFactory class that are creating our phones depending on what type we pass in, and we get rid of the actual logic from the consumers. Now lets create a couple of phones.

const samsung = PhoneFactory. create('Samsung'); const iphone = PhoneFactory. create('IPhone'); // Print: Calling with my samsung samsung.call() // Print: Calling with my IPhone iphone.call()

There we have it. Our PhoneFactory will now handle the logic to create our phones. And depending on the type, we will get different output from the call() function.

Summary

Now that we have explored the Factory pattern, we can list the pros and cons with it.

Pros

  • Simple creation of objects from the consumers
  • Hide complexity of the creation
  • Scalable, easy to create more types of sub classes

Cons

  • Need for a lot of classes

Hope you enjoyed it. Have a good day!

signatureSun Mar 19 2023
See all our articles