本文介绍了JavaScript中的工厂模式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望将JavaScript对象的创建与使用它的代码分离,以便我可以灵活地将一个对象实现替换为具有相同签名的其他对象实现,而无需触及大部分代码。为了实现这一点,我想出了Repository和Factory Method的概念来创建对象。以下是实现:

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");

这种模式对我有用,但在我开始在我的项目中实现此代码之前我想要知道是否存在任何陷阱(模式创建对象失败,性能瓶颈 - 如果我将创建5到10个200到1000行代码的对象)使用这种方法。我在使用服务器端代码很长一段时间后回到JavaScript,所以我对我的解决方案不是很有信心。此外,我本可以使用ES5 Object.create,但客户现在仍然使用IE8和FF3.6浏览器。

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.

谢谢

推荐答案

只需使用 Object.create()以及这样的ES5垫片:

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

它可以完成您想要的大部分工作,并且在实际成为标准时为ES5提供方式。鉴于使用一个对象作为另一个对象的原型的常见情况,它在所有浏览器中都能正常工作。

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.

这篇关于JavaScript中的工厂模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-14 01:02