(function(window, undefined) {
var modules = {};
var Sky = {
//定义模块的基本信息
// 1、模块名称, 2、模块的依赖, 3、产生实例的工厂
define: function(moduleName, dependencies, factory) {
if (!modules[moduleName]) {
//模块信息
var module = {
moduleName: moduleName,
dependencies: dependencies,
factory: factory
};
modules[moduleName] = module;
}
return modules[moduleName];
},
//使用依赖
use: function(moduleName) {
var module = modules[moduleName];
//产生单个实例
if (!module.instance) {
var instances = [];
var len = module.dependencies.length - 1;
for (var i = 0; i <= len; i++) {
var dependency = module.dependencies[i],
instance = dependency.instance;
if (instance) {
instances.push(instance);
} else {
//递归,将每次产生的实例放入数组
instances.push(arguments.callee(dependency));
}
}
//生成实例
module.instance = module.factory.apply(null, instances);
}
return module.instance;
}
};
window.Sky = Sky || {};
})(window);
Sky.define("constant.PI", [], function() {
return 3.1415926;
});
Sky.define("shape.Circle", ["constant.PI"], function(pi) {
function Circle(r) {
this.r = r || 0;
};
Circle.prototype.area = function() {
return pi * this.r * this.r;
};
return Circle;
});
Sky.define("shape.Rectangle", [], function() {
function Rectangle(width, height) {
this.width = width || 0;
this.height = height || 0;
};
Rectangle.prototype.area = function() {
return this.width * this.height;
};
return Rectangle;
});
Sky.define("ShapeTypes", ["shape.Circle", "shape.Rectangle"], function(Circle, Rectangle) {
return {
'CIRCLE': Circle,
'RECTANGLE': Rectangle
};
});
Sky.define("ShapeFactory", ["ShapeTypes"], function(ShapeTypes) {
return {
getShape: function(type) {
var shape;
switch (type) {
case 'CIRCLE':
shape = new ShapeTypes[type](arguments[1]);
break;
case 'RECTANGLE':
shape = new ShapeTypes[type](arguments[1], arguments[2]);
break;
}
return shape;
}
};
});
var ShapeFactory = Sky.use("ShapeFactory");
console.log(ShapeFactory.getShape("CIRCLE").area());
console.log(ShapeFactory.getShape("RECTANGLE", 2, 3).area());
https://www.talkingcoder.com/article/6275833765160419328