Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 453
Henry Avatar asked Dec 06 '25 09:12

Henry


1 Answers

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:

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)...
OR it will return null.

Maybe null isn't what you want.
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.

like image 125
Norguard Avatar answered Dec 07 '25 22:12

Norguard



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!