Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR TYPESCRIPT

factory design pattern typescript

abstract class Ecomerce {
   abstract products(): Record<string, any>[]
}

class Tokopedia extends Ecomerce {
  products(): Record<string, any>[] {
     return [
      {name: 'PS4', price: 5000000},
      {name: 'PSV', price: 3500000},
      {name: 'Gameboy', price: 350000}
     ]
  }
}

class Bukalapak extends Ecomerce {
  products(): Record<string, any>[] {
     return [
      {name: 'PS4', price: 4500000},
      {name: 'PSV', price: 2500000},
      {name: 'Gameboy', price: 250000}
     ]
  }
}

class Shopee extends Ecomerce {
  products(): Record<string, any>[] {
     return [
      {name: 'PS4', price: 3500000},
      {name: 'PSV', price: 1500000},
      {name: 'Gameboy', price: 150000}
     ]
  }
}

// delacation factory metode here

interface EcomerceFactory {
   getEcomerce(name: string): Tokopedia | Bukalapak | Shopee
}

class EcomerceFactory implements EcomerceFactory {
  getEcomerce(name: string): Tokopedia | Bukalapak | Shopee {
      if(name.toLowerCase() == 'tokopedia') {
         return new Tokopedia()
      } else if(name.toLowerCase() == 'bukalapak') {
         return new Bukalapak()
      } else if(name.toLowerCase() == 'shopee') {
         return new Shopee()
      }
  }
}

const res = new EcomerceFactory()
const tokopedia = res.getEcomerce('tokopedia')
const bukalapak = res.getEcomerce('bukalapak')
const shopee = res.getEcomerce('shopee')

console.log(`Tokopedia: ${tokopedia.products()}`)
console.log(`Bukalapak: ${bukalapak.products()}`)
console.log(`Shopee: ${shopee.products()}`)
 
PREVIOUS NEXT
Tagged: #factory #design #pattern #typescript
ADD COMMENT
Topic
Name
6+4 =