gpt4 book ai didi

没有 if-else block 的 JavaScript 工厂模式

转载 作者:行者123 更新时间:2023-11-30 07:24:37 25 4
gpt4 key购买 nike

我想知道是否有更好的方法来实现 createEmployee(),它使用字典或其他一些方法来快速查找所请求的类型,而不是 if-else block 。

function Clerk( options ) {
this.hourRate = options.hourRate || 20;
this.firstName = options.firstName || "no first name";
this.lastName = options.lastName || "no last name";
this.id = options.id || "-9999999999";
}

function Manager( options) {
this.hourRate = options.hourRate || 200;
this.firstName = options.firstName || "no first name";
this.lastName = options.lastName || "no last name";
this.id = options.id || "-9999999999";
this.yearBonus = options.yearBonus || "200000";
}

function Teacher( options) {
this.hourRate = options.hourRate || 100;
this.firstName = options.firstName || "no first name";
this.lastName = options.lastName || "no last name";
this.id = options.id || "-9999999999";
this.subject = options.subject || "history";
}

var EmployeesFactory = function() {};

EmployeesFactory.prototype.createEmployee = function (options) {
if(options.employeeType == "Clerk")
employeeConstructor = Clerk;
else if(options.employeeType == "Manager")
employeeConstructor = Manager;
else if(options.employeeType == "Teacher")
employeeConstructor = Teacher;
return new employeeConstructor(options);
}

var factory = new EmployeesFactory();
var person = factory.createEmployee( {
employeeType: "Manager",
firstName: "Haim",
lastName: "Michael",
id: 234234234 } );

document.write(person instanceof Manager);

最佳答案

试试这个:

var constructors;

constructors = {
"Clerk" : function (options) {
// your constructor code here for clerks
},
"Manager" : function (options) {
// your constructor code here for managers
},
"Teacher" : function (options) {
// your constructor code here for teachers
}
};

EmployeesFactory.prototype.createEmployee = function (options) {
return constructors[options.employeeType](options);
};

我建议将 constructors 对象很好地隐藏在 EmployeesFactory 中。通过这种方式,您还可以删除不需要的函数名称(ClerkManagerTeacher)。

此外,您应该只创建一次constructors 对象并在创建过程中重复使用它。不要在创建时实例化它。您可以通过以下方式执行此操作:

var EmployeesFactory = function () {
var constructors;

constructors = {
"Clerk" : function (options) {
// your constructor code here for clerks
},
"Manager" : function (options) {
// your constructor code here for managers
},
"Teacher" : function (options) {
// your constructor code here for teachers
}
};

return {
"create" : function (options) {
return constructors[options.employeeType](options);
}
};
};

你可以这样得到工厂:

factory = EmployeesFactory();

并且可以这样创建东西:

factory.create(options);

所有东西都将舒适并隐藏在外层封闭内,没有内脏卡在外面。

工厂模式的目的是隐藏对象构建的复杂性和细节,因此将方法围绕用于消费在一个方面上遗漏了(我承认, minor/minimal) 的模式。通过使用闭包,您也可以获得隐藏的好处。

关于没有 if-else block 的 JavaScript 工厂模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21684529/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com