Factory Pattern in JavaScript

2019-04-29 12:04发布

问题:

I want to decouple the creation of JavaScript objects from the code that is using it so that I have the flexibility of replacing one object implementation with other object implementation having same signature without touching much of the code. In order to achieve this I come up with the concept of Repository and a Factory Method to create objects. Here is the implementation:

//The Factory Method
function ObjectFactory() {}
ObjectFactory.create = function (o) {
    var args = [].slice.call(arguments, 1);

    function F() {}
    F.prototype = o.prototype;
    var instance = new F();
    o.apply(instance, args);
    return instance;
};

//The Repository
var Repository = {
    'invitation': Invitation,
    'message': Message
};

//Usage
var inv = ObjectFactory.create(Repository["invitation"], "invitation", "invitation body", "Sender");
var msg = ObjectFactory.create(Repository["message"], "message", "message body");
var inv2 = ObjectFactory.create(Repository["invitation"], "invitation2", "invitation body2", "Sender");

This pattern is working for me but before I go ahead and implement this code in my project I want to know are there any pitfalls(failure of pattern to create objects, performance bottlenecks - if I'll create 5-10 objects of 200 to 1000 lines of code) using this approach. I am returning to JavaScript after working on server side code for a long time so I am not very confident of my solution. Also, I could have used ES5 Object.create but the customer is stuck with IE8 and FF3.6 browsers for now.

Thanks

回答1:

Just use Object.create() along with an ES5 shim like this: https://github.com/kriskowal/es5-shim/blob/master/es5-shim.js

It does most of what you want, and does things the ES5 way for when that actually becomes standard. Given the common case of using one object as the prototype for another, it works fine in all browsers.