发布时间:2025-12-10 23:30:21 浏览次数:1
这是一种特殊的方法,用于在分配内存后初始化新创建的对象。由于 JavaScript 通常是面向对象的,它最常处理对象,因此我打算深入研究对象构造函数。在JavaScript中可以通过三种方式创建新对象:
以下是创建构造函数设计模式的一种方法。
//ThiscreatesanewemptyObjectvarnewObject={};//ThiscreatesanewemptyObjectvarnewObject=Object.create(Object.prototype);varnewObject=newObject();要访问函数的属性,您需要初始化对象。
constobject=newConstructorObject();
因此,上面的 new 关键字告诉 JavaScript aconstructorObject应该充当构造函数。继承是这种设计模式不支持的一件事。在此处了解更多详细信息。
原型模式基于原型继承,由此创建的对象充当其他对象的原型。实际上,原型充当创建的每个对象构造函数的蓝图。
例子
varmyCar={name:"Ford",brake:function(){console.log("Stop!Iamapplyingbrakes");}Panic:function(){console.log("wait.howdoyoustopthuisthing?")}}//useobjeccreatetoinstansiateanewcarvaryourCar=object.create(myCar);//Youcannowseethatoneisaprototypeoftheotherconsole.log(yourCar.name);]在模块设计模式中,对原型模式进行了改进。模块模式中设置了不同类型的修饰符(私有和公共)。您可以在没有冲突的情况下创建类似的函数或属性。公开重命名函数具有灵活性。令人生畏的部分是无法从外部环境覆盖创建的函数。
例子
functionAnimalContainter(){constcontainer=[];functionaddAnimal(name){container.push(name);}functiongetAllAnimals(){returncontainer;}functionremoveAnimal(name){constindex=container.indexOf(name);if(index<1){thrownewError('Animalnotfoundincontainer');}container.splice(index,1)}return{add:addAnimal,get:getAllAnimals,remove:removeAnimal}}constcontainer=AnimalContainter();container.add('Hen');container.add('Goat');container.add('Sheep');console.log(container.get())//Array(3)["Hen","Goat","Sheep"]container.remove('Sheep')console.log(container.get());//Array(2)["Hen","Goat"]在只需要创建一个实例的场景中是必不可少的,例如一个数据库连接。只能在连接关闭时创建实例,或者确保在打开新实例之前关闭打开的实例。这种模式也被称为严格模式,与这种模式相关的一个缺点是它在测试中的艰巨体验,因为它隐藏的依赖对象不容易被挑出来进行测试。
例子
functionDatabaseConnection(){letdatabaseInstance=null;//tracksthenumberofinstancescreatedatacertaintimeletcount=0;functioninit(){console.log(`Openingdatabase#${count+1}`);//nowperformoperation}functioncreateIntance(){if(databaseInstance==null){databaseInstance=init();}returndatabaseInstance;}functioncloseIntance(){console.log('closingdatabase');databaseInstance=null;}return{open:createIntance,close:closeIntance}}constdatabase=DatabseConnection();database.open();//Opendatabase#1database.open();//Opendatabase#1database.open();//Opendatabase#1database.close();//closedatabase它是一种创建对象,无需构造函数即可创建对象。它提供了创建对象的通用接口,我们可以在其中指定要创建的工厂对象的类型。因此,我们只指定对象,工厂实例化并返回给我们使用。当对象组件设置具有高度复杂性并且当我们想要根据所处环境轻松创建对象的不同实例时,使用工厂模式是明智的。当处理许多对象时,我们也可以使用工厂模式共享相同属性的小对象以及在组合需要解耦的对象时。
例子
//DealerADealerA={};DealerA.title=functiontitle(){return"DealerA";};DealerA.pay=functionpay(amount){console.log(`setupconfigurationusingusername:${this.username}andpassword:${this.password}`);return`Paymentforservice${amount}issuccessfulusing${this.title()}`;};//DealerBDealerB={};DealerB.title=functiontitle(){return"DealerB";};DealerB.pay=functionpay(amount){console.log(`setupconfigurationusingusername:${this.username}andpassword:${this.password}`);return`Paymentforservice${amount}issuccessfulusing${this.title()}`;};//@param{*}DealerOption//@param{*}configfunctionDealerFactory(DealerOption,config={}){constdealer=Object.create(dealerOption);Object.assign(dealer,config);returndealer;}constdealerFactory=DealerFactory(DealerA,{username:"user",password:"pass"});console.log(dealerFactory.title());console.log(dealerFactory.pay(12));constdealerFactory2=DealerFactory(DealerB,{username:"user2",password:"pass2"});console.log(dealerFactory2.title());console.log(dealerFactory2.pay(50));观察者设计模式在对象与其他对象集同时通信的地方很方便。在这种观察者模式中,没有不必要的跨状态推拉事件,而是涉及的模块只修改数据的当前状态。
例子
functionObserver(){this.observerContainer=[];}Observer.prototype.subscribe=function(element){this.observerContainer.push(element);}//thefollowingremovesanelementfromthecontainerObserver.prototype.unsubscribe=function(element){constelementIndex=this.observerContainer.indexOf(element);if(elementIndex>-1){this.observerContainer.splice(elementIndex,1);}}/***wenotifyelementsaddedtothecontainerbycalling*eachsubscribedcomponentsaddedtoourcontainer*/Observer.prototype.notifyAll=function(element){this.observerContainer.forEach(function(observerElement){observerElement(element);});}最后,我想说命令设计模式结束了我对 JavaScript 设计模式的 7 个**总结。命令设计模式将方法调用、操作或请求封装到单个对象中,以便我们可以自行决定传递方法调用。命令设计模式让我们有机会从任何执行命令的对象发出命令,并将责任委托给不同的对象。这些命令以run()和execute()格式显示。
(function(){varcarManager={//informationrequestedrequestInfo:function(model,id){return"Theinformationfor"+model+"withID"+id+"isfoobar";},//nowpurchasethecarbuyVehicle:function(model,id){return"YouhavesuccessfullypurchasedItem"+id+",a"+model;},//nowarrangeaviewingarrangeViewing:function(model,id){return"Youhavesuccessfullybookedaviewingof"+model+"("+id+")";}};})();读到这里,这篇“JavaScript设计模式有哪些及怎么实现”文章已经介绍完毕,想要掌握这篇文章的知识点还需要大家自己动手实践使用过才能领会,如果想了解更多相关内容的文章,欢迎关注本站行业资讯频道。