javascript工厂模式

来源:互联网 发布:linux 文件传输工具 编辑:程序博客网 时间:2024/05/23 18:00

简单工厂模式

通过对产品类的抽象使其创建业务主要负责用于创建多类的产品实例.
简单工厂类有三个角色:

  • 工厂角色
    它是工厂模式的核心,它负责实现创建所有实例的内部逻辑,会根据它所包涵的一个静态方法调用时传递的参数来决定创建的对象。
  • 对象类角色
    它是工厂模式在调用静态方法创建对象时的对象类。
  • 具体对象角色
    它是工厂模式最终创建的对象,所有创建的对象都是某一个对象类的实例。
var Alert=function(text){};var Prompt=function(text){};var Confirm=function(text){};function createPop(type,text){    var o=new Object();    o.content=text;    o.show=function(){    };    if(type=="alert"){        new Alert(o.content);    }    if(type=="prompt"){        new Prompt(o.content);    }    if(type=="confirm"){        new Confirm(o.content);    }    return o;}

工厂方法模式

通过对产品类的抽象使其创建业务主要负责用于创建多类产品实例

var Factory=function(type,content){    if(this instanceof Factory){        var s=new this[type](content);    }else{        return new Factory(type,content);    }}Factory.protype={    Java:function(content){         this.content=content;        (function(content){            var div=document.createElement('div');            div.innerHTML=content;            div.style.color="red";            div.style.border="1px solid red";            document.getElementById('container').appendChild(div);        })(content);    },    Javascript:function(content){         this.content=content;        (function(content){            var div=document.createElement('div');            div.innerHTML=content;            div.style.border="1px solid red";            document.getElementById('container').appendChild(div);        })(content);    },    UI:function(content){        this.content=content;        (function(content){            var div=document.createElement('div');            div.innerHTML=content;            div.style.border="1px solid red";            document.getElementById('container').appendChild(div);        })(content);    }}

抽象工厂模式

通过对类的工厂抽象使其业务用于对产品类簇的创建。

var VehicleFactory=function(subType,superType){    if(typeof VehicleFactory[superType]==='function'){        function F(){};        F.prototype=new VehicleFactory[superType]();        subType.constructor=subType;        subType.prototype=new F();    }else{        throw new Error("未创建该抽象类")    }};VehicleFactory.Car=function(){    this.type='car';};//小汽车抽象类VehicleFactory.Car.prototype={    getPrice:function(){        return new Error('抽象方法不能调用');    },    getSpeed:function(){        return new Error('抽象方法不能调用');    }};//公交车抽象类VehicleFactory.Bus=function(){    this.type='bus';};VehicleFactory.Bus.prototype={    getPrice:function(){        return new Error('抽象方法不能调用');    },    getSpeed:function(){        return new Error('抽象方法不能调用');    }};var BMW=function(price,speed){    this.price=price;    this.speed=speed;    VehicleFactory(BMW,'Car');};BMW.prototype.getPrice=function(){    return this.price;};BMW.prototype.getSpeed=function(){    return this.speed;};var bmw=new BMW(1111111,213);console.log(bmw.getPrice());
0 0