1. 工厂模式
作用:实现对象的批量创建
/* 构造函数 */
function Person(name) {
this.name = name;
}
function Car(model) {
this.model = model;
}
/* 创建 */
function create(type, val) {
return (this instanceof create) ?
this[type](val) : new create(type, val);
}
create.prototype = {
person: Person,
car: Car
}
console.log(create('person', 'zhangsan'))
console.log(new create('car', 'bwm'))
2. 原型模式
作用:创建一个共享原型,通过拷贝这个原型来创建新的类
// 也可以是其他类的原型
let prototype = {
say() {
console.log(this.name);
}
}
function Person() {
function F() { };
F.prototype = prototype;
let f = new F();
f.name = "zhansan";
return f;
}
new Person().say();// zhansan
3. 建造者模式
作用:将创建对象的细节分为创建子对象的过程,使结构更加清晰
/* 实现 */
function Person(name) {
this.name = name;
}
function CreateName(name) {
this.wholeName = name;
[this.firstName, this.lastName] = name.split(' ');
}
function CreateWork(workName) {
switch (workName) {
case 'engineer':
this.workName = "工程师";
this.desc = "热爱编程";
break;
case 'teacher':
this.workName = "老师";
this.desc = "热爱分享";
break;
default:
this.workName = workName;
this.desc = "无";
}
}
CreateWork.prototype.changeWork = function (workName, desc) {
workName && (this.workName = workName);
desc && (this.desc = desc);
}
/* 创建类 */
function Candidate(params) {
let _candidate = new Person();
_candidate.name = new CreateName(params.name);
_candidate.work = new CreateWork(params.work);
return _candidate;
}
/* 举例 */
let arr = [
{ name: "zhang san", work: "engineer" },
{ name: "li si", work: "teacher" }
];
let candidates = [];
arr.forEach(v => {
candidates.push(new Candidate(v));
})
console.log(candidates[0]);
candidates[0].work.changeWork('学生', '热爱学习');
console.log(candidates[0]);
4. 单例模式
作用:实现无论创建多少个对象都返回同一个
const createSingle = (function () {
let _unique = null;// 私有变量
return function () {
if (_unique === null) {
_unique = { a: 1 };
}
return _unique;
}
})();
let single1 = createSingle();
let single2 = createSingle();
console.log(single1 === single2);// true