创建类模式
<table id="roster"></table>
<script>
var rootElement = document.getElementById('roster');
function Student(name, gender, score) {
this.name = name;
this.gender = gender;
this.score = score;
this.quality = 100;
this.mount();
}
Student.prototype.sumScore = function () {
return this.score + this.quality;
}
/**
* 将数据转换为HTML并插入到表格中
*/
Student.prototype.mount = function () {
var tr = document.createElement('tr');
tr.innerHTML =
'<td>' + this.name + '</td>' +
'<td>' + this.gender + '</td>' +
'<td>' + this.score + '</td>' +
'<td>' + this.quality + '</td>' +
'<td>' + this.sumScore() + '</td>'
;
rootElement.appendChild(tr);
}
var whh = new Student('王花花', '男', 98);
var lsd = new Student('李拴蛋', '女', 50);
</script>
构造模式
<script>
let studentCount = 0;
class Student {
}
class StudentBuilder {
constructor() {
this.student = new Student();
}
setName(name) {
this.student.name = name;
}
setGender(gender) {
if (gender != '男' && gender != '女')
throw '好玩不';
this.student.gender = gender;
}
setHairLength(hairLength) {
if (
(this.student.gender == '男' && hairLength > 1) ||
(this.student.gender == '女' && hairLength > 25)
) throw '回去剪头';
this.student.hairLength = hairLength;
}
build() {
studentCount++;
console.log(studentCount);
return this.student;
}
}
const builder = new StudentBuilder();
builder.setName('王花花');
builder.setGender('男');
builder.setHairLength(1);
const whh = builder.build();
const builder2 = new StudentBuilder();
builder2.setName('李拴蛋');
builder2.setGender('女');
builder2.setHairLength(20);
const lsd = builder2.build();
console.log(lsd);
</script>
工厂模式
<script>
function Student(name, subjects) {
this.name = name;
// ...
// 如果是文科生:['政治', '历史', '地理']
// 如果是理科生:['数学', '物理', '化学']
this.subjects = subjects;
}
/**
* 创建学生
* @param {string} name 姓名
* @param {string} type 文科还是理科
* @return {Student}
*/
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 '没有这个专业,别瞎填';
}
}
var whh = factory('王花花', '文科');
var lsd = factory('李拴蛋', '理科');
var zks = factory('赵可爽', '体育');
var lbb = factory('刘备备', '撒盐');
console.log(whh);
console.log(lsd);
console.log(zks);
</script>
网友评论