做工厂有什么比这更好的方法吗?

时间:2017-04-28 17:05:15

标签: javascript

我创建了一个这样的工厂来创建一个特定的对象,具体取决于select值:

let myFactory = { "CREATE_DOCTOR" : function(){return new Doctor();}
                  "CREATE_NURSE" : function(){return new Nurse();}          
                  "CREATE_PATIENT" : function(){return new Patient();}
                };
let aPerson=[];

mySelect.addEventListener("change", function(){
  aPerson.push(myFactory["CREATE_"+mySelect.options[mySelect.selectedIndex].value]());
}

当然,我拥有可以在工厂中创建的所有类,mySelect可以获得对html选择的引用。但我的问题是......是否有(甚至)更好的方法来做到这一点?因为我知道的另一种方法是做一个非常大的if / else考虑所有替代方案,这使得代码不易维护。

1 个答案:

答案 0 :(得分:2)

不需要那些包装函数,select元素具有value属性,因此:

var classes = {
    DOCTOR:  Doctor,
    NURSE:   Nurse,
    PATIENT: Patient
};
mySelect.addEventListener("change", function(){
    aPerson.push(new classes[mySelect.value]());
});

示例:

function Doctor() {
  console.log("Creating a Doctor");
}
function Nurse() {
  console.log("Creating a Nurse");
}
function Patient() {
  console.log("Creating a Patient");
}
var classes = {
    DOCTOR:  Doctor,
    NURSE:   Nurse,
    PATIENT: Patient
};
var aPerson = [];
var mySelect = document.getElementById("mySelect");
mySelect.addEventListener("change", function(){
    aPerson.push(new classes[mySelect.value]());
});
<select id="mySelect">
  <option value="DOCTOR">Doctor</option>
  <option value="NURSE">Nurse</option>
  <option value="PATIENT">Patient</option>
</select>

就此而言,所有大写字母都没有必要。在ES2015 +兼容的JavaScript引擎上,它可能只是:

const classes = {
    Doctor,
    Nurse,
    Patient
};
mySelect.addEventListener("change", function(){
    aPerson.push(new classes[mySelect.value]());
});

...选择中的值为"Doctor""Nurse""Patient"

示例:

class Doctor {
  constructor() {
    console.log("Creating a Doctor");
  }
}
class Nurse {
  constructor() {
    console.log("Creating a Nurse");
  }
}
class Patient {
  constructor() {
    console.log("Creating a Patient");
  }
}
const classes = {
    Doctor,
    Nurse,
    Patient
};
const aPerson = [];
const mySelect = document.getElementById("mySelect");
mySelect.addEventListener("change", function(){
    aPerson.push(new classes[mySelect.value]());
});
<select id="mySelect">
  <option>Doctor</option>
  <option>Nurse</option>
  <option>Patient</option>
</select>