Advertisement
SergioG_0823849

factory

Apr 4th, 2024 (edited)
779
0
305 days
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // define facory as a meta-class
  2.  
  3. class Employee {
  4.   create (type) {
  5.     let employee
  6.     if (type === 'fulltime') {
  7.       employee = new FullTime()
  8.     } else if (type === 'parttime') {
  9.       employee = new PartTime()
  10.     } else if (type === 'temporary') {
  11.       employee = new Temporary()
  12.     } else if (type === 'contractor') {
  13.       employee = new Contractor()
  14.     }
  15.     employee.type = type
  16.     employee.say = function () {
  17.       console.log(`${this.type}: rate ${this.rate}/hour`)
  18.     }
  19.   }
  20. }
  21.  
  22. // define classes for every job type
  23. class Fulltime {
  24.   constructor () {
  25.     this.rate = '$12'
  26.   }
  27. }
  28.  
  29. class PartTime {
  30.   constructor () {
  31.     this.rate = '$11'
  32.   }
  33. }
  34.  
  35. class Temporary {
  36.   constructor () {
  37.     this.rate = '$10'
  38.   }
  39. }
  40.  
  41. class Contractor {
  42.   constructor () {
  43.     this.rate = '$15'
  44.   }
  45. }
  46.  
  47. // usage example
  48. // create new factory
  49. const factory = new Employee()
  50. fulltime = factory.create('fulltime')
  51. parttime = factory.create('parttime')
  52. temporary = factory.create('temporary')
  53. contractor = factory.create('contractor')
  54.  
  55. // use it
  56. fulltime.say()
  57. parttime.say()
  58. temporary.say()
  59. contractor.say()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement