📜  工厂设计模式打字稿代码示例

📅  最后修改于: 2022-03-11 14:48:26.105000             🧑  作者: Mango

代码示例1
abstract class Ecomerce {
   abstract products(): Record[]
}

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

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

class Shopee extends Ecomerce {
  products(): Record[] {
     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()}`)