js设计模式
创建性设计模式
安全模式
创建实例时,为了保证被new关键字正确调用,可在构造函数中加入对this指向的判断。
const Factory = function(...args){ if(this instanceof Factory){ ... return new this(args) }else{ return new Factory(...args) } }简单工厂模式(静态工厂)
// 创建单独一类对象 function Factory(name,age,gender){ const o = {} o.name = name o.age = age o.gender = gender o.say = function(){ console.log("my name is"+ this.name) } return o }工厂方法模式
// 创建多类对象 function Factory(...args){ ... } Factory.prototype = { Product1:function(){ // 简单工厂 }, Product2:function(){ //简单工厂 } }抽象工厂模式
抽象类:没有任何属性,并且原形上的方法都被限制不能使用。- 作用:假设子代都可能调用一些该类的必要方法,如果只是调用而不重写该方法,则会调用类上的被限制的版本而得到错误提示。
const Car = function(){} Car.prototype = { getPrice:function(){ return new Error("抽象方法不能调用") }, getSpeed:function(){ return new Error("抽象方法不能调用") } }
js设计模式
http://yoursite.com/2021/09/09/js设计模式/