0
点赞
收藏
分享

微信扫一扫

前端设计模式


为什么使用设计模式?

设计模式是一套被反复使用的、多数人知晓的、经过分类编目的、代码设计经验的总结。

使用设计模式是为了重用代码、让代码更容易被他人理解、保证代码可靠性。

什么是设计模式

设计模式构成:

模式名称:模式的名字
环境和问题:描述在什么环境下出现什么特定的问题
解决方案:描述如何解决方案
效果:描述应用该模式后的效果,以及可能带来的问题
注意:设计模式的种类很多,各个模式都有它对应的场景,不能武断地认为某个模式就是最优的解决方案

第一、代理模式

// 声明女孩对象
var girl = function (name) {
this.name = name;
};
// 声明男孩对象
var boy = function (girl) {
this.girl = girl;
this.sendGift = function (gift) {
console.log("Hi " + girl.name + ", 男孩送你一个礼物:" + gift);
}
};
// 声明代理对象
var proxyObj = function (girl) {
//this.girl = girl;
this.sendGift = function (gift) {
var b = new boy(girl);
b.sendGift(gift); // 替dudu送花咯
}
};
var proxy = new proxyObj(new girl("花花"));
proxy.sendGift("999朵玫瑰");

第二 、观察者模式

class Subject{//发布者
constructor(){//构造器
this.subs = []; //订阅列表--数组
}
addSub(sub){//方法
this.subs.push(sub);
}
notify(food){//通知订阅者
this.subs.forEach(sub=> {
sub.update(food);
});
}
}
class Observer{//订阅者
constructor(name, food){ //订阅外卖名字
this.name = name;
this.food = food;
}
update(food){
if(food===this.food){
console.log(this.name + "的外卖:"+food);
}
}
}
var subject = new Subject(); //实例化发布者
var tom = new Observer("tom","地三鲜"); //实例化订阅者
var jack = new Observer("jack","红烧肉");
//目标添加观察者了
subject.addSub(tom);
subject.addSub(jack);
//目标发布消息调用观察者的更新方法了
subject.notify("地三鲜");
subject.notify("红烧肉");

第三、单例模式

class Store {
action() {
console.log('vue store.')
}
}
// 定义一个静态的方法,将方法挂载到class上面,无论SingleObject被new多少个,getInstance的方法只有一个
Store.getInstance = (function() {
let instance
return function() {
if (!instance) {
instance = new Store();
}
return instance
}
})()

// js中的单例模式只能靠文档去约束,不能使用private关键字去约束
// 测试:注意这里只能使用静态函数getInstance,不能使用new Store()
let obj1 = Store.getInstance()
obj1.action()
let obj2 = Store.getInstance()
obj2.action()

// 单例模式(唯一的),每次获取的都是一个东西,所以他两相等,否则就不是单例模式
console.log(obj1 === obj2) //true

第四、工厂模式

// function
var MobileFactory = (function () {
var Mobile = function (name,model){
this.model = model;
this.name = name;
};
Mobile.prototype.play=function(){
console.log("Mobile:"+this.name+"-"+this.model)
}
return function (name,model) {
return new Mobile(name,model);
};
})();

var p6 = MobileFactory("iphone", "6");
var px = MobileFactory("iphone", "X");
p6.play()
px.play()


class Product {
constructor(name, model) {
this.name = name
this.model = model;
}
play(){
console.log("Mobile:"+this.name+"-"+this.model)
}
}

class FactoryCreator {
create(name,model) {
return new Product(name,model)
}
}
let creator = new FactoryCreator()
// 通过工厂省城product的实例
let p = creator.create('iphone',"6")
p.play();
let p2 = creator.create('iphone',"7")
p2.play()

第五、装饰器模式

class Circle {
draw() {
console.log('我要画一个圆')
}
}

class CircleDecorator {
constructor(circle) {
this.circle = circle
}
draw() {
this.circle.draw()
this.setBorder(circle)
}
setBorder(circle) {
console.log('加上边框')
}
}
// 想引用某个类的时候将他实例化,以参数的形式进行传递进去
let circle = new Circle()
circle.draw()
console.log('+++++')
let dec = new CircleDecorator(circle)//把原实例对象传入到一个新装饰对象中
dec.draw()


举报

相关推荐

0 条评论