javascript设计模式--工厂方法模式

工厂方法模式

将实际创建对象工作推迟到子类当中。
1.安全模式类,用new和不用new都能够得到预期的对象。

    var Demo = function(){}
    Demo.prototype = {
        show : function(){
            console.log('成功获取');
        }
    }
    var d = new Demo();
    d.show();//成功获取
    var d = Demo();
    d.show();//uncaught typeerror:cannot read peoperty show of undefined

解决办法:在构造函数开始时先判断当前对象this指代是不是类(demo),如果是则通过new关键子创建对象,

    var Demo = function(){
        if(!(this instanceof Demo)){
            return new Demo;    
        }
    }
    var d = Demo();
    d.show();

2.安全的工厂方法

    var Factory = function(type,content){
        if(this instanceof Factory){
            var s = new this[type](content);
            return s;
        }
        else{
            return new Factory(type,content);
        }
    }
    //工厂原型中设置创建所有类型数据对象的基类
    Factory.prototype = {
        Java:function(content){
            ...
        }
        javascript:function(content){
            ...
        }
    }

你可能感兴趣的:(JavaScript,设计模式,函数,对象)