一: 简单工厂模式:
假设: 飞机大战. 两种飞机, 一种 smallPlane, 一种 bigPlane. 构造函数分别是
- function SmallPlane(die){
- this.height = 100;
- this.width = 100;
- this.die = function(){console.log('die')}
- }
- function BigPlane(){
- this.height = 200;
- this.width = 200;
- this.die = function(){console.log('die')}
- }
简单工厂模式可以写一个简单的工厂模式,
- function factoryPlane (fun){
- var plane = null
- switch(fun){
- case SmallPlane : plane = new SmallPlane();break;
- case BigPlane : plane = new BigPlane();break;}
- plane.die = function(){console.log('die')};// 可以吧单个的制造函数
- return plane;
- }
这种简单的工厂模式可以实现对多有工厂事例的集中管理. --- 当给他们都添加某个属性时候, 可以在工厂函数里直接添加.
可以方便的扩展工厂里的子类 --- 但违反开闭原则;
工厂模式不是制造具体的事例对象的, 而是制造构造函数的. 当需要有好多构造函数, 且构造函数之间有共同点, 可以用工厂模式来管理这些有联系的构造函数.
来源: http://www.bubuko.com/infodetail-2887817.html