1、单例模式
class LoginForm {
constructor() {
this.state = "hide";
}
show() {
if (this.state === "show") {
alert("已经显示");
return;
}
this.state = "show";
console.log("登录框显示成功");
}
hide() {
if (this.state === "hide") {
alert("已经隐藏");
return;
}
this.state = "hide";
console.log("登录框隐藏成功");
}
}
LoginForm.getInstance = (function () {
let instance;
return function () {
if (!instance) {
instance = new LoginForm();
}
return instance;
};
})();
let obj1 = LoginForm.getInstance();
obj1.show();
let obj2 = LoginForm.getInstance();
obj2.hide();
console.log(obj1 === obj2);
2、观察者模式
// 主题 保存状态,状态变化之后触发所有观察者对象
class Subject {
constructor() {
this.state = 0;
this.observers = [];
}
getState() {
return this.state;
}
setState(state) {
this.state = state;
this.notifyAllObservers();
}
notifyAllObservers() {
this.observers.forEach((observer) => {
observer.update();
});
}
attach(observer) {
this.observers.push(observer);
}
}
// 观察者
class Observer {
constructor(name, subject) {
this.name = name;
this.subject = subject;
console.log(this);
this.subject.attach(this);
}
update() {
console.log(`${this.name} update, state: ${this.subject.getState()}`);
}
}
// 测试
let s = new Subject();
let o1 = new Observer("o1", s);
let o2 = new Observer("02", s);
s.setState(12);
3、装饰器模式
/*模拟传统语言的装饰者
装饰者模式将一个对象嵌入到另一个对象之中,
实际上相当于这个对象被另一个对像包装起来,形成一条包装链。
请求随着这条包装链依次传递到所有的对象,每个对象都有处理这条请求的机会。
*/
//原始的飞机类
var Plan = function () {};
Plan.prototype.fire = function () {
console.log('发射普通子弹');
};
//装饰类
var MissileDecorator = function (plan) {
this.plan = plan;
};
MissileDecorator.prototype.fire = function () {
this.plan.fire();
console.log('发射导弹!');
};
var plan = new Plan();
plan = new MissileDecorator(plan);
plan.fire();
4、工厂模式
//1.工厂应该由厂长来决定运行到底哪条产品线
//2.消费者-》子类
var gongchang = {};
gongchang.chanyifu = function () {
this.gongren = 50;
console.log('我们有' + this.gongren);
};
gongchang.chanxie = function () {
this.gongren = 100;
console.log('产鞋子');
};
gongchang.yunshu = function () {
this.gongren = 10;
console.log('运输');
};
gongchang.changzhang = function (para) {
return new gongchang[para]();
};
var me = gongchang.changzhang('chanxie');
console.log(me, me.gongren);
网友评论