前端设计模式浅谈
不多说,直接上代码
构造器模式
-
es5
function Student(name,sex,score){ this.name = name; this.sex = sex; this.score = score; this.quantity = 100; this.sumScore = function(){ return this.score + this.quantity; } } const zsf = new Student('张三丰','男',97); console.log(zsf.name,zsf.sumScore()) -
es6
class Student { constructor(name,sex,score){ this.name = name; this.sex = sex; this.score = score; this.quantity = 100; } sumScore(){ return this.score + this.quantity; } } const zsf = new Student('张三丰','男',97); console.log(zsf.name,zsf.sumScore())
原型模式
将方法抽离出来
function Student(name,sex,score){
this.name = name;
this.sex = sex;
this.score = score;
this.quantity = 100;
}
Student.prototype.sumScore = function(){
return this.score + this.quantity;
}
构建者模式
-
es5
var studentCount = 0; function Student(){} function StudentBuild(){ this.student = new Student(); this.setName = function(name){ this.student.name = name; } this.setSex = function(sex){ this.student.sex = sex; } this.build = function(){ studentCount++; console.log(studentCount); return this.student; } } var builder = new StudentBuild(); builder.setName('张三丰'); builder.setSex('男'); var zsf = builder.build(); console.log(zsf) -
es6
let studentCount = 0; class Student{} class StudentBuild{ constructor(){ this.student = new Student() } setName(name){ this.student.name = name; } setSex(sex){ this.student.sex = sex; } build(){ studentCount++; console.log(studentCount); return this.student; } } const builder = new StudentBuild(); builder.setName('张三丰'); builder.setSex('男'); const zsf = builder.build(); console.log(zsf)
工厂模式
//工厂模式
function Student(name,subjects){
this.name = name;
//如果是文科生:['政治','历史','地理']
//如果是理科生:['物理','化学','生物']
this.subjects = subjects;
}
function factory(name,type){
switch (type) {
case '文科':
return new Student(name,['政治','历史','地理']);
break;
case '理科':
return new Student(name,['物理','化学','生物']);
break;
case '体育生':
return new Student(name,['长跑','...']);
break;
default:
throw '没有这个专业,别瞎填';
break;
}
}
var zsf = factory('张三丰','理科');
console.log(zsf)
抽象工厂模式
//抽象工厂
function Student(){
this.info = '我是一个学生';
}
function Teacher(){
this.info = '我是一名老师';
}
function studentFactory(){
return new Student();
}
function teacherFactory(){
return new Teacher();
}
function abstractFactory(factory){
switch (factory) {
case 'student':
return studentFactory;
break;
case 'teacher':
return teacherFactory;
break;
default:
throw '没有这个工厂';
break;
}
}
var factory = abstractFactory('teacher');
var user = factory('张三丰','理科');
console.log(user);
单例模式
//单例模式
function Resource(){
// 如果不是第一次new,instance肯定是存在的
if(Resource.instance){
return Resource.instance;
}else{ //否则,instance不存在
//组装新对象
this.balance = 100;
//将其存在Resource机器上
Resource.instance = this;
}
}
var r = new Resource();
console.log('r:', r);
r.balance = 50;
console.log('r:', r);
var r2 = new Resource();
console.log('r:', r2);
r.balance = 55;
console.log('r:', r2);

浙公网安备 33010602011771号