观察者模式:
<script type="text/javascript">
// Subject(小宝宝)
class Subject{
constructor(name){
//小宝宝的状态
this.name = name;
this.state = "开心";
this.observers = []; //放观察者的
}
// attach 需要将观察者放到自身中
attach(ther){
this.observers.push(ther);
}
// 改变状态,
setState(state){
this.state = state;
//状态更新后,要通过给观察者
this.observers.forEach(ther=>{
ther.update(this);
})
}
}
class Observer{
constructor(name){
this.name = name;
}
//观察小宝宝的状态
update(baby){
console.log(this.name+":"+baby.name +"现在的状态是:"+baby.state);
}
}
let baby = new Subject("小宝宝");
let father = new Observer("爸爸");
let mother = new Observer("妈妈");
baby.attach(father);
baby.attach(mother);
baby.setState("不开心");
</script>
发布订阅者模式
<script type="text/javascript">
// 发布者, 订阅者 , 出版社
var ChuBanShe={
_authorArr :[], //所有的订阅者
on(author){
this._authorArr.push(author);
},
emit(value){ //发布 ,推送给订阅者
this._authorArr.forEach(item=>{
//console.log(item.xxxx);
item.read(value);
})
}
}
ChuBanShe.on({"name":"张三",age:18,msg:"", read:function(value){
console.log(this.name+"读取",value)
}})
ChuBanShe.on({"name":"李四",age:18,msg:"", read:function(value){
console.log(this.name+"读取",value)
}})
ChuBanShe.on({"name":"王五",age:18,msg:"", read:function(value){
console.log(this.name+"读取",value)
}})
ChuBanShe.emit("今日分享,设计模式,好好理解 ")
</script>
工厂模式
<script type="text/javascript">
var msgFactory = function (type,value) {
if(this instanceof msgFactory){
return new this[type](value);
}else{
return new msgFactory(type,value);
}
}
msgFactory.prototype = {
email: function (value) {
var reg = /^ [ A-Za-z0-9!# $ %&'"“” + /= ? ^ _`{} | ~, ( ) :;<> [ ] - . ] * @ [ A-Za -z0-9- ] * . [ A-Za-z ] + ( ?: . [ A-Za-z ] + ) ? ( ?: . [ A-Za-z ] + ) ? $/;
if (reg.test(value)) {
this.msg= "ok"
} else {
this.msg= "邮件格式不正确"
}
},
phone: function (value) {
var reg = /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/;
if (reg.test(value)) {
this.msg = "ok"
} else {
this.msg = "手机号码格式不正确"
}
},
identity: function (value) {
var reg = /^[1-9]\d{5}(18|19|([23]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/;
if (reg.test(value)) {
this.msg = "ok"
} else {
this.msg = "身份证格式不正确"
}
}
}
let result =new msgFactory("phone","13699212345");
console.log(result)
</script>
单例模式:
<script type="text/javascript">
var btn = document.getElementById("btnZheZhao");
var div;
btn.onclick = function () {
createZheZhao();
}
</script>