Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

javascript 设计模式(工厂方法模式) #22

Open
wl05 opened this issue May 16, 2019 · 0 comments
Open

javascript 设计模式(工厂方法模式) #22

wl05 opened this issue May 16, 2019 · 0 comments

Comments

@wl05
Copy link
Owner

wl05 commented May 16, 2019

本系列文章来源于《Javascript设计模式》(张容铭版),做一个记录。

到现在为止虽然只读了两章,但真的感受到了设计模式中思想的精妙。

在上一篇javascript设计模式(简单工厂模式)中我们通过简单工厂模式来创建我们需要的对象,但是如果现在又有新的类需要加入进来,我们需要修改两处,我们不仅要添加新的类,而且还需要修改工厂函数。那有没有这样的方法使得我们以后每需要一个类的时候我们就只需要添加这个类就行了,其他的我们就不用管了呢,答案就是“工厂方法模式”

概念

我们可以将工厂方法看作是一个实例化对象的的工厂类。为了安全起见,这里我们采用安全模式类,而我们将创建对象的基类放在工厂方法类的原型中即可。

安全模式类

安全模式类就是防止我们用错误的方式使用类。我们知道创建一个实例我们需要使用new 关键字,但是如果我们忽略了new关键,得到结果并不是我们想要的。例如:

function Demo() {
    this.name = "占三"
}

var demo = new Demo()
console.log(demo.name) // 张三
var demo = Demo()
console.log(demo.name) // Uncaught TypeError: Cannot read property 'name' of undefined

如何解决这个问题呢,很简单我们在我们构造函数中先判断当前this对象是不是继承自Demo(原文这里是说判断当前对象this指代是不是类Demo,instanceof是判断实例是不是属于某个类,所以我觉得这种说法有待商榷)。

function Demo() {
    this.name = "张三"
    if (!(this instanceof Demo)) {
        return new Demo()
    }
}
var demo = new Demo()
console.log(demo.name) // 张三
var demo = Demo()
console.log(demo.name) // 张三

实现工厂方法

var Factory = function (type, content) {
    // 运用安全模式类
    if (this instanceof Factory) {
        var s = new this[type](content); // 这里是调用Factory原型中对应的构造函数
        return s;
    } else {
        return new Factory(type, content)
    }
}
// 工厂原型中设置创建所有类型数据对象的基类
Factory.prototype = {
    constructor: Factory, // 原文中这里没有将Factory.prototype.constructor 重新指向Factory
    Java: function (content) {
        // ......
    },
    Javascript: function (content) {
        // ......
    },
    php: function (content) {
        // ......
    }
}

这里我们可以看出如果以后还想添加其他类时,只需要在Factory的原型里面添加相应的类就可以了。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant