本文主要是介绍JavaScript设计模式,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
// author:pandaHe
// time:2021.10.27
// tips:reading sharing ~~
// -- 1 -- DES:{工厂模式}
function Animal(opts) {
let obj = new Object();
obj.color = opts.color;
obj.name = opts.name;
obj.getInfo = function () {
return "名称:" + obj.name + "颜色:" + obj.color;
};
return obj;
}
let cat = Animal({ name: "山猫", color: "黑色" });
// console.log(cat);
// -- 2 -- DES:{工厂模式}
class User {
constructor(name = "", viewPage = []) {
if (new.target === User) {
throw new Error("抽象类不能实例化!");
}
this.name = name;
this.viewPage = viewPage;
}
}
class UserFactory extends User {
constructor(name, viewPage) {
super(name, viewPage);
}
create(role) {
switch (role) {
case "superAdmin":
return new UserFactory("超级管理员", [
"⾸⻚",
"通讯录",
"发现⻚",
"应⽤数据",
"权限管理",
]);
break;
case "admin":
return new UserFactory("普通管理员", ["⾸⻚", "通讯录", "发现⻚"]);
bteak;
}
}
}
let userFactory = new UserFactory();
let superAdmin = userFactory.create("superAdmin");
let admin = userFactory.create("admin");
// console.log(superAdmin);
// console.log(superAdmin);
// -- 3 -- DES:{工厂模式}
function getAbstractUserFactory(type) {
switch (type) {
case "wechat":
return "UserOfWechat";
break;
case "qq":
return "UserOfQq";
break;
case "weibo":
return "UserOfWeibo";
break;
default:
throw new Error("参数错误, 可选参数:wechat、qq、weibo");
}
}
let WechatUserClass = getAbstractUserFactory("wechat");
let QqUserClass = getAbstractUserFactory("qq");
let WeiboUserClass = getAbstractUserFactory("weibo");
// let wechatUser = new WechatUserClass("微信⼩李");
// let qqUser = new QqUserClass("QQ⼩李");
// let weiboUser = new WeiboUserClass("微博⼩李");
// console.log(WechatUserClass);
// console.log(QqUserClass);
// console.log(WeiboUserClass);
// -- 4 -- DES:{单例模式)}
class Singleton {
constructor() {}
}
Singleton.getInstance = (function () {
let instance;
return function () {
if (!instance) {
instance = new Singleton();
}
return instance;
};
})();
let s1 = Singleton.getInstance();
let s2 = Singleton.getInstance();
// console.log(s1 === s2); // true
// -- 5 --DES:{异常处理/方案切换/适配模式}
var googleMap = {
show: function () {
console.log("开始渲染⾕歌地图");
},
};
var baiduMap = {
display: function () {
console.log("开始渲染百度地图");
},
};
var baiduMapAdapter = {
show: function () {
return baiduMap.display();
},
display: function () {
return baiduMap.show();
},
};
var renderMap = function (map) {
if (map.show instanceof Function) {
map.show();
}
if (map.display instanceof Function) {
map.display();
}
};
// renderMap(googleMap);
// renderMap(baiduMap);
// -- 6 --!!bug@readonly!! --DES:{添加额外的东西/装饰器模式}
// function readonly(target, key, descriptor) {
// descriptor.writable = false;
// return descriptor
// };
// class Test {
// @readonly
// name = 'yck'
// };
// let t = new Test();
// t.yck = '111'
let newArray = [];
[{ name: "apple" }, { name: "pandaHe" }].map((item) => {
newArray.push(Object.assign({}, item, { check: false }));
});
// console.log(newArray)
// -- 7 https://es6.ruanyifeng.com/#docs/proxy DES:{中间拦截}
var obj = {};
var proxy = new Proxy(obj, {
get: function (target, key, receiver) {
// console.log(`getting ${key}!`);
return Reflect.get(target, key, receiver);
},
set: function (target, key, value, receiver) {
// console.log(`setting ${key}!`);
return Reflect.set(target, key, value, receiver);
},
});
proxy.count = 1; // setting count!
++proxy.count; // getting count!
// setting count! // 2
// console.log(obj.count) // 2
// -- 8 -- DES:{一对多/发布订阅模式}
class Subject { constructor() {
this.observers = []; // 观察者列表
}
// 添加
add(observer) { this.observers.push(observer); };
// 删除
remove(observer) { let idx = this.observers.findIndex(item => item === observer); idx > -1 && this.observers.splice(idx, 1); }
// 通知
notify() { for (let observer of this.observers) { observer.update(); } } };
// 观察者类
class Observer { constructor(name) { this.name = name; };
// ⽬标对象更新时触发的回调
update() { console.log(`⽬标者通知我更新了,我是:${this.name}`); } };
// 实例化⽬标者
let subject = new Subject();
// 实例化两个观察者
let obs1 = new Observer('前端开发者');
let obs2 = new Observer('后端开发者');
// 向⽬标者添加观察者
subject.add(obs1); subject.add(obs2);
// ⽬标者通知更新
// subject.notify(); // 输出: // ⽬标者通知我更新了,我是前端开发者 // ⽬标者通知我更新了,我是后端开发
// -- 9 DES:{多对多}
// 事件中⼼
let pubSub = {
list: {},
// {onwork:[fn1,fn2],offwork:[fn1,fn2],launch:[fn1,fn2]}
subscribe: function (key, fn) {
// 订阅
if (!this.list[key]) { this.list[key] = []; };
this.list[key].push(fn);
},
publish: function(key, ...arg) {
// 发布
for(let fn of this.list[key]) {
fn.call(this, ...arg);
}
},
unSubscribe: function (key, fn) {
// 取消订阅
let fnList = this.list[key];
if (!fnList) return false; if (!fn) {
// 不传⼊指定取消的订阅⽅法,则清空所有key下的订阅
fnList && (fnList.length = 0);
} else {
fnList.forEach((item, index) => { if (item === fn) { fnList.splice(index, 1); } }) } }
};
// 订阅
pubSub.subscribe('onwork', time => { console.log(`上班。:${time}`); });
pubSub.subscribe('offwork', time => { console.log(`下班啦~~:${time}`); });
pubSub.subscribe('launch', time => { console.log(`吃饭啦~~:${time}`); })
// 发布
// pubSub.publish('offwork', '18:00:00');
// pubSub.publish('launch', '12:00:00');
// pubSub.publish('onwork', '9:00:00');
// 取消订阅
// pubSub.unSubscribe('onwork');
// end
这篇关于JavaScript设计模式的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!