当前位置: 首页 > Web前端 > HTML

【通过理解】JS设计模式·工厂模式

时间:2023-03-28 13:49:12 HTML

工厂模式概念工厂模式没有暴露创建对象的具体逻辑,而是将逻辑封装在一个函数中,创建大量类似的对象,那么这个函数就可以算是一个工厂。工厂模式按抽象程度可分为:简单工厂、工厂方法和抽象工厂。优点通过工厂模式,我们可以快速创建大量相似的对象,而无需重复代码。缺点工厂模式创建的对象属于Object,无法区分对象类型,这也是工厂模式应用不广泛的原因。Thecoderealizesthesimplefactorymode(static)://Example:classifythekingheroesondemand,andproduceconstpersonList=[{person:['Daji','XiaoQiao','ZhouYu','WangZhaojun']},{person:['LiBai','AKe','LanlingKing','HanTiaotiao']},{person:['CaoAman','KaiDaddy','Miyamoto']}]letwangzhe=function(personType){functionFashi(){this.person=personList[0].person}functionCike(){this.person=personList[1].person}functionZhanshi(){this.person=personList[2].person}switch(personType){case'fashi':returnnewFashi();break;case'cike':returnnewCike();break;case'zhanshi':returnnewZhanshi();break;default:thrownewError('parametererror,optionalparameters:fashi,cike,zhanshi');}}//callletfashi=wangzhe('fashi');letcike=wangzhe('cike');letzhanshi=wangzhe('zhanshi');fashi.peson//['Daji','XiaoQiao','ZhouYu','WangZhaojun']//es6writing:classWangzhe{constructor(opt){this.person=opt.人;}staticgetPersonList(personType){switch(personType){case'fashi':returnnewwangzhe(personList[0]);休息;case'cike':returnnew王者(personList[1]);休息;case'战事':returnnewwangzhe(personList[2]);休息;default:thrownewError('参数错误,可选参数:fashi,cike,zhanshi');}}}//调用wangzhe.getPersonList('fashi').person//['妲己','小乔','周瑜','王昭君']