[英]How to implement Factory design pattern with RequireJS?
I have something like this... 我有这样的事......
define(['ClassA', 'ClassB', 'ClassC'],
function(ClassA, ClassB, ClassC)
{
return {
build: function(className) {
var obj;
switch(className)
{
case 'ClassA': obj = new ClassA(); break;
case 'ClassB': obj = new ClassB(); break;
case 'ClassC': obj = new ClassC(); break;
}
return obj;
}
}
}
This seems ok but is there a better way to write it? 这似乎没问题,但有没有更好的方法来编写它? I tried replacing switch to
我尝试将开关更换为
return new arguments[className](); // doesn't work
The closest I can get to is to use a map: 我最接近的是使用地图:
var classes = {
ClassA: ClassA,
ClassB: ClassB,
ClassC: ClassC
}
return new classes[className]();
Is there a better way? 有没有更好的办法?
There's really no problem with your object there. 那里你的对象真的没问题。
It's fast, efficient and easy to follow. 它快速,高效且易于遵循。
The only suggestion I'd have is to create a var to hold the value, or to test more-explicitly if className
is a suitable string, and is in fact in your list: 我唯一的建议是创建一个var来保存值,或者更明确地测试
className
是否是一个合适的字符串,并且实际上在你的列表中:
Either: 或者:
var construct = classes[className];
if (construct) { return new construct(); }
else { /* handle the case where the class doesn't exist */ }
Or: 要么:
return classes[className] && (new classes[className]()) || null;
The second checks for classes[className] and should return a new instance if it exists (JS returns the value on the very right of AND)... 第二个检查类[className]并且应该返回一个新实例(如果它存在)(JS返回AND右边的值)...
OR it will return null
. 或者它将返回
null
。
Maybe null
isn't what you want. 也许
null
不是你想要的。
But the point is that you should be prepared to handle somebody passing: "Bob"
to your factory, despite the fact that there is no Bob
class. 但重点是你应该准备好处理一个人:
"Bob"
到你的工厂,尽管事实上没有Bob
班。
Using Function Modules as Factories : 使用功能模块作为工厂 :
define(function(require){
var classes = {
'ClassA' : require('ClassA'),
'ClassB' : require('ClassB'),
'ClassC' : require('ClassC')
};
return function(className){
try {
return new classes[className];
} catch(error) {
throw new Error('Unknown className Specified.');
}
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.