工厂类:
/** * Created by zzq on 2015/5/15. */ module.exports = function(){ this.getProduct = function(){ console.log('重写这个方法获得相应的产品对象!'); } }
产品A:
/** * Created by zzq on 2015/5/15. */ var product = require('./product'); var util = require('util'); var productA = function(){ product.call(this); this.getProduct = function(){ console.log('获得了产品A对象!'); } } util.inherits(productA, product); module.exports = productA;
产品B类与A写法相同。。。
简单产品工厂:
/** * Created by zzq on 2015/5/15. */ var productA = require('./productA'); var productB = require('./productB'); var _instance = null; var productFactoryModule = function(){ var productFactory = function(){ } productFactory.prototype.selectProduct = function(type) { switch (type) { case 'productA': { return new productA(); };break; case 'productB': { return new productB(); };break; } } this.initProduct = function (type) { if(_instance === null){ _instance = new productFactory(); } return _instance.selectProduct(type); } } //控制Single module.exports = productFactoryModule;
mainApp:
/** * Created by zzq on 2015/5/15. */ var productFactory = require('./productFactory'); var productA = new productFactory(); productA.initProduct('productA').getProduct();